package com.ecom.park_jy;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestHandle;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.SyncHttpClient;
import com.loopj.android.http.TextHttpResponseHandler;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Dictionary;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Timer;
import java.util.TimerTask;
import java.lang.String;
import java.io.File;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;


import cz.msebera.android.httpclient.Header;

public class opening extends AppCompatActivity {
    private static final String WRITE_EXTERNAL_STORAGE = "android.permission.WRITE_EXTERNAL_STORAGE";
    private static final String READ_EXTERNAL_STORAGE = "android.permission.READ_EXTERNAL_STORAGE";
    private static final String CAMERA = "android.permission.CAMERA";
    private static final String ACCESS_FINE_LOCATION = "android.permission.ACCESS_FINE_LOCATION";
    private static final String ACCESS_COARSE_LOCATION = "android.permission.ACCESS_COARSE_LOCATION";
    private static final String ACCESS_LOCATION_EXTRA_COMMANDS = "android.permission.ACCESS_LOCATION_EXTRA_COMMANDS";
    public static final String PARK = "PARK";
    public static final String PARK_USER = "PARK_USER";
    TextView textView, textView10;
    Handler handler = new Handler();
    String path = Environment.getExternalStorageDirectory() + "/Park_JY/";
    String user = "";
    File dir, up;
    Button btn2, btn21;
    private Calendar calendar;
    public String pref_FtpAddr = "192.168.3.2";
    public int pref_FtpPort = 21;
    public String pref_FtpUser = "cypark";
    public String pref_FtpPsw = "ecom2828";
    public int pref_UploadT = 2;
    public static long nFtpTimes = 0;
    public static long nTimeCounter = 0;
    private static Timer timer;
    private FtpConn mFtpClient;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_opening);
        textView = (TextView) findViewById(R.id.textView);
        textView10 = (TextView) findViewById(R.id.textView10);
        btn2 = (Button) findViewById(R.id.button2);
        btn21 = (Button) findViewById(R.id.button21);

        handler.removeCallbacks(uptime); //設定定時要執行的方法
        handler.postDelayed(uptime, 0);  //更新時間
        int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE, CAMERA, ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION, ACCESS_LOCATION_EXTRA_COMMANDS}, 0);
        }

        dir = new File(path);
        up = new File(path + "upload");
        if (!dir.exists() || !up.exists()) {
            dir.mkdirs();
            up.mkdirs();
        }
        timer = new Timer(true);
        timer.schedule(timerTask, 1000, 1000);
        receiveData();

        //Intent intent = new Intent(this,MainService.class);   //執行背景程式
        //startService(intent);
    }

    @Override
    public void onStart() {
        super.onStart();
        SaveUser();
    }

    public void SaveUser() {
        SharedPreferences shared = getSharedPreferences(PARK, 0);
        user = shared.getString(PARK_USER, "");
        if (user.contains("01")) {
            user = user.substring(1);
        }
        if (!"".equals(user)) {
            textView10.setText(user);
        } else {
            textView10.setText("請設定使用者");
        }
    }

    public void bt_exit(View view) {
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    public void bt_start(View view) {
        if (textView10.getText().toString().equals("請設定使用者")) {
            new AlertDialog.Builder(this).setTitle("設定").setMessage("請設定使用者").setPositiveButton("確定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            }).show();
        } else {
            Intent intent = new Intent();
            intent.setClass(this, Start.class);
            intent.putExtra("Morning", btn2.getText().toString());
            intent.putExtra("PU", user);
            startActivity(intent);
        }

    }

    public void bt_night(View v) {
        if (textView10.getText().toString().equals("請設定使用者")) {
            new AlertDialog.Builder(this).setTitle("設定").setMessage("請設定使用者").setPositiveButton("確定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            }).show();
        } else {
            Intent intent = new Intent();
            intent.setClass(this, Start.class);
            intent.putExtra("Night", btn21.getText().toString());
            intent.putExtra("PU", user);
            startActivity(intent);
        }

    }

    private Runnable uptime = new Runnable() {
        @Override
        public void run() {
            handler.postDelayed(this, 1000);
            Date d = new Date();
            SimpleDateFormat year = new SimpleDateFormat("yyyy");
            SimpleDateFormat date = new SimpleDateFormat("MM/dd");
            SimpleDateFormat time = new SimpleDateFormat("HH:mm:ss");
            int y = Integer.parseInt(year.format(d)) - 1911;
            textView.setText(Integer.toString(y) + "/" + date.format(d) + "  " + time.format(d));
        }
    };

    public void bt_set(View v) {
        Intent intent = new Intent();
        intent.setClass(this, Setting.class);
        intent.putExtra("USER_2", user);
        startActivity(intent);

    }


    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            android.os.Process.killProcess(android.os.Process.myPid());
        }
        return true;
    }

    public void receiveData() {
        final RequestParams params = new RequestParams();
        final AsyncHttpClient client = new AsyncHttpClient();
        final String Url = "http://192.168.3.240/v1/";
        //final ProgressDialog mp = new ProgressDialog(opening.this);
        final String[] isfinish = {""};
        final int[] b = {0};


        /*mp.setCancelable(false);
        mp.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mp.setTitle("下載中...");
        mp.setMessage("正在下載資料，請稍後~");
        mp.setMax(26);
        mp.setIndeterminate(false);
        mp.show();*/


        //Type
        //client = new AsyncHttpClient();
        client.get(Url + "vehicle/types", params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                isfinish[0] = "車種：接收失敗";
                Toast.makeText(opening.this, isfinish[0], Toast.LENGTH_LONG).show();
            }

            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                b[0]++;
                String[] type;
                type = s.replace("\"", "").split(";");
                try {
                    FileOutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory() + "/Park_JY/TypeOfCar.temp");
                    try {
                        BufferedWriter w = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
                        try {
                            for (int c = 0; c < type.length; c++) {
                                w.write(type[c] + "\n");
                            }
                            w.flush();
                            w.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                isfinish[0] = "車種：接收成功";
                Toast.makeText(opening.this, isfinish[0], Toast.LENGTH_LONG).show();
            }
        });

        //路段
        //client = new AsyncHttpClient();
        client.get(Url + "roads", params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                isfinish[0] = "接收失敗";
                Toast.makeText(opening.this, "路段" + isfinish[0], Toast.LENGTH_LONG).show();
            }

            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                isfinish[0] = "路段：接收成功";
                Toast.makeText(opening.this, isfinish[0], Toast.LENGTH_LONG).show();
//                }                                                     //測試讀取到的資料
                        try {
                            FileOutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory() + "/Park_JY/JiaYiCityRoad.txt");
                            //System.out.println("say some thing");//回報測試
                                BufferedWriter w = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
                             s = s.replace("\"", "").replace(";", "\n");

                            w.write(s);
                            w.flush();
                            w.close();
                                    //final Queue<RequestHandle> roadCount = new LinkedList<RequestHandle>();       //沒用到
                                            client.get( "http://192.168.3.240:80/v1/grids" , params, new TextHttpResponseHandler() {
                                                @Override
                                                public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                                                    //System.out.println("is failure, try again.");//回報測試

                                                }

                                                @Override
                                                public void onSuccess(int i, Header[] headers, String s) {
                                                    //System.out.println("is success.");//回報測試
                                                        try {
                                                            for(int count=0;count<27;count++) {
                                                                String Grids = new JSONArray(s).getJSONObject(count).getString("Grid");
                                                                String Road = new JSONArray(s).getJSONObject(count).getString("Road");             //提取API的json格式資料

                                                                FileOutputStream eee = new FileOutputStream(Environment.getExternalStorageDirectory() + "/Park_JY/" + Road + ".temp");
                                                                OutputStreamWriter eeee = new OutputStreamWriter(eee);                                    //存檔設定
                                                                String[] Rows_arr = Grids.replace("[", "").replace("]", "").replace("\"", "").split(",");

                                                                final int arr_size = (Rows_arr.length) / 14;
                                                                System.out.println(arr_size);
                                                                for (int num_in = 0; num_in < arr_size; num_in++) {                                       //各別讀取資料


                                                                    String Grid = new JSONArray(Grids).getJSONArray(num_in).toString();
                                                                    String Rows = Grid.replace("[", "").replace("]", "").replace("\"", "").replace(",", " ");

                                                                    System.out.println(count + "===" + Road + "===---->" + Rows);       //註解
                                                                    eeee.write(Rows + "\n");//資料寫入
                                                                }

                                                                eeee.flush();
                                                                eeee.close();           //關閉資料寫入
//                                                        }
                                                            }


                                                        } catch(JSONException e) {
                                                            e.printStackTrace();
                                                        }
                                                        catch (FileNotFoundException e) {

                                                            e.printStackTrace();
                                                        }
                                                        catch (IOException e) {
                                                            e.printStackTrace();
                                                        }


                                                }
                                            });

                                    System.out.println("Thanks God");//回報測試

                        }
//                        catch (InterruptedException e) {
//                            e.printStackTrace();
//                        }
                        catch (FileNotFoundException e) {

                            e.printStackTrace();
                        }
                        catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        catch (IOException e) {
                            e.printStackTrace();
                        }

            }
        });

        /*
        for (int r = 0; r < roadCount.length; r++) {    //讀取roadCount陣列的資料量跑迴圈
            final int rr = r;           //精美的宣告
            client.post(Url + "grids?road_id=" + roadCount[rr], params, new TextHttpResponseHandler() {
                @Override
                public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                    Toast.makeText(opening.this, roadCount[rr], Toast.LENGTH_LONG).show();
                }

                @Override
                public void onSuccess(int i, Header[] headers, String s) {
                    String[] roadNum, roadNum2;
                    roadNum = s.replace("\"", "").split(";");               //用replace組合文字再用split將;移開並分割文字

                    try {
                        FileOutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory() + "/Park_JY/" + roadCount[rr] + ".temp");
                        try {
                            BufferedWriter w = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));  //用W寫入緩衝
                            try {
                                for (int c = 0; c < roadNum.length; c++) {
                                    if (!roadNum[c].substring(roadNum[c].indexOf("")).equals("\n")) {
                                        w.write(roadNum[c] + "\n");

                                        try {
                                            w.flush();          //強制輸出緩衝的資料
                                            w.close();
                                            isfinish[0] = "格號：接收成功" + roadCount[rr];
                                            Toast.makeText(opening.this, isfinish[0], Toast.LENGTH_LONG).show();
                                            Thread.sleep(1000);
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }
                                    }

                                }
//                                w.flush();          //強制輸出緩衝的資料
//                                w.close();
//                                isfinish[0] = "格號：接收成功" + roadCount[rr];
                            } catch (IOException e) {               //I/O錯誤
                                e.printStackTrace();
                            }
                        } catch (UnsupportedEncodingException e) {          //編碼不支援
                            e.printStackTrace();
                        }
                    } catch (FileNotFoundException e) {         //找無檔案例外
                        e.printStackTrace();
                    }
                    //isfinish[0] = "格號：接收成功" + roadCount[rr];
                    //Toast.makeText(opening.this, isfinish[0], Toast.LENGTH_LONG).show();
                }
            });

        }
        */  //修改前的樣式


        //抓取GPS
        client.get("http://192.168.3.240:1000/v1/insert/record", 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) {
                try {
                    FileOutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory() + "/Park_JY/ALL_GPS.txt");
                    BufferedWriter w = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @SuppressWarnings("static-access")
    public void UploadFiles(String szPath, String szExt) throws IOException {
        File fileTemp = new File(szPath);
        int length;

        if (!fileTemp.isDirectory())
            return;

        if (!mFtpClient.connect(pref_FtpAddr, pref_FtpPort, pref_FtpUser, pref_FtpPsw))
            return;

        String szYYMMDD = Commin.getDate(calendar, false);
        String szUserId = user.split(",")[0];
        length = fileTemp.listFiles(new FilesFilter(szUserId, szYYMMDD, szExt, false)).length;
        if (length > 0) {
            for (File file : fileTemp.listFiles(new FilesFilter(szUserId, szYYMMDD, szExt, false))) {
                String szPathTemp = szPath + "/" + file.getName();
                File fTemp = new File(szPathTemp);

                if (fTemp.exists() && mFtpClient.stor(fTemp) && szExt.equals(".txt"))
                    fTemp.delete();
            }
        }

        mFtpClient.disconnect();
    }

    TimerTask timerTask = new TimerTask() {
        public void run() {
            Message message = new Message();

            if ((++nTimeCounter) >= 60 * pref_UploadT) {
                nTimeCounter = 0;
                message.what = 1;
            } else
                message.what = 0;

            handlerMsg.sendMessage(message);
        }
    };
    final Handler handlerMsg = new Handler() {
        @SuppressWarnings("static-access")
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                new Thread() {
                    public void run() {
                        try {
                            nFtpTimes = 0;
                            String szPath = path + "upload";
                            UploadFiles(szPath, ".txt");

                            nFtpTimes = 0;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }.start();

            } else {
                calendar = Calendar.getInstance();
                //textView.setText(Commin.getDateAndTime(calendar));

//                if ((++nFtpTimes) > 60 * (pref_UploadT - 1))
//                    try {
//                        System.out.println("No~~~~");
//                        mFtpClient.disconnect();
//                        nFtpTimes = 0;
//                    } catch (IOException e) {
//                        System.out.println("G8~~~");
//                        e.printStackTrace();
//                    }
            }

            super.handleMessage(msg);
        }
    };

}
