package com.ecom.park_jy;

import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.os.Vibrator;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
import android.widget.Toast;


import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.SyncHttpClient;
import com.loopj.android.http.TextHttpResponseHandler;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cz.msebera.android.httpclient.Header;


public class MainService extends Service {
    String time2 = "";
    String findin,findout;
    String[] readfile,filec;
    String readfile2,ip;
    //List list = new ArrayList();
    int count = 0;
    RequestParams params = new RequestParams();
    SyncHttpClient client = new SyncHttpClient();
    Vibrator vibrator;
    @Override
    public int onStartCommand(final Intent intent, final int flags, int startId){
        ip = "http://192.168.3.240:";
        // 設定每次時間觸發時執行的動作，將這些動作包成物件，放進 TimerTask 型態的參考中。
        TimerTask action = new TimerTask() {
            @Override
            public void run() {
                final String[] roadCount = {"A117","B240","C265","D004","E089","F010","F020","G042","H076","I072","J042","K006","L007","L329","M055","N058","P075","Q083","R018","S038","T138","U064","V119","W108","X151","Y015"};
                Date d = new Date();
                SimpleDateFormat year = new SimpleDateFormat("yyyy");
                SimpleDateFormat simple = new SimpleDateFormat("MMddHHmm");
                int x = 0;
                x = Integer.valueOf(year.format(d)) - 1911;
                readfile2 = Integer.toString(x) + simple.format(d);
                params.put("update_datetime",time2);
                for(int r = 0; r < roadCount.length; r++){
                    client.get(ip + "1/v1/select/grids/" + roadCount[r], params, new TextHttpResponseHandler() {
                        @Override
                        public void onFailure(int i, Header[] headers, String s, Throwable throwable) {

                        }
                        @Override
                        public void onSuccess(int i, Header[] headers, String s) {
                            String[] msg,timechange;
                            msg = s.replace("\"","").split(";");
                            try {
                                FileOutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory() +"/Park_JY/" + "update_U064.txt");
                                try {
                                    BufferedWriter w = new BufferedWriter(new OutputStreamWriter(out,"UTF-8"));
                                    for(int j = 0; j < msg.length; j++){
                                        timechange = msg[j].split(" ");
                                        if(timechange[11].equals("None") && (Integer.parseInt(msg[j].substring(1,4)) % 2 == 1) && !(msg[j].substring(0,4).equals("U061")) && !(msg[j].substring(0,4).equals("U063")) && !(msg[j].substring(0,4).equals("U065")) && !(msg[j].substring(0,4).equals("U067")) && (Integer.parseInt(msg[j].substring(1,4)) < 84)){
                                            w.write(msg[j] + "\n");
                                        }else{
                                            w.write(msg[j] + "\n");
                                        }
                                    }
                                    w.flush();
                                    w.close();
                                } catch (UnsupportedEncodingException e) {
                                    e.printStackTrace();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }

                            Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                            Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);

                            vibrator = (Vibrator)getSystemService(Service.VIBRATOR_SERVICE);
                            //long[] hz = {0,300,100,200};
                            vibrator.vibrate(1000);
                            r.play();
                            //list = new ArrayList();
                        }
                    });
                }
                //time2 = readfile2;
            }
        };

        // 將定時器物件建立出來。
        Timer timer = new Timer();
        // 利用 schedule() 方法，將執行動作、延遲時間(1秒)、間隔時間(1秒) 輸入方法中。
        // 執行此方法後將會定時執行動作。
        timer.schedule(action, 10000, 60000);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

}
