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.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.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.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.SyncHttpClient;
import com.loopj.android.http.TextHttpResponseHandler;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

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(){
        RequestParams params = new RequestParams();
        AsyncHttpClient client = new AsyncHttpClient();
        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) {

            }
            @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();
                if(isfinish[0].equals("接收失敗")){
                    //mp.dismiss();
                }
            }
            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                isfinish[0] = "路段：接收成功";
                //Toast.makeText(opening.this, isfinish[0],Toast.LENGTH_LONG).show();
                final String[] road;
                final int[] a = {0};
                road = s.replace("\"","").split(";");
                a[0] = 0;
                if(isfinish[0].equals("路段：接收成功")){
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                FileOutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory() +"/Park_JY/JiaYiCityRoad.txt");
                                try {
                                    BufferedWriter w = new BufferedWriter(new OutputStreamWriter(out,"UTF-8"));
                                    try {
                                        for(int c = 0; c < road.length-1; c++){
                                            if(!road[c].substring(road[c].indexOf("")).equals("\n")){
                                                w.write(road[c] + "\n");
                                            }
                                            //mp.setProgress(a[0]++);
                                            Thread.sleep(50);
                                        }
                                        w.flush();
                                        w.close();

                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                } catch (UnsupportedEncodingException e) {
                                    e.printStackTrace();
                                }
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }
                            //mp.dismiss();
                        }
                    }).start();
                }
            }
        });

        //格號
        final String[] roadCount = {"A117","B240","C265","D004","E089","F010","F020","G042","H076","I072","J042","K006","L007","L329","M055","N058","P075","Q083","R018","S038","S001","T138","U064","V119","W108","X151","Y015"};
        for(int r = 0; r < roadCount.length; r++){
            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) {

                }
                @Override
                public void onSuccess(int i, Header[] headers, String s) {
                    String[] roadNum,roadNum2;
                    roadNum = s.replace("\"","").split(";");

                    try {
                        FileOutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory() +"/Park_JY/" + roadCount[rr] + ".temp");
                        try {
                            BufferedWriter w = new BufferedWriter(new OutputStreamWriter(out,"UTF-8"));
                            try {
                                for(int c = 0; c < roadNum.length; c++){
                                    if(!roadNum[c].substring(roadNum[c].indexOf("")).equals("\n")){
                                        w.write(roadNum[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();
                }
            });
        }

        //抓取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
                    {
                        mFtpClient.disconnect();
                        nFtpTimes = 0;
                    } catch (IOException e)
                    {
                        e.printStackTrace();
                    }
            }

            super.handleMessage(msg);
        }
    };

}
