package com.app.espcontroler;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.bottomappbar.BottomAppBar;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    Button btnOn, btnOff;
    TextView txtStatus,txtDevices;
    String TargetIP,TargetDevice;
    FloatingActionButton fabExit;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txtDevices = (TextView)findViewById(R.id.Devices);
        txtStatus = (TextView)findViewById(R.id.Status);
        btnOn = (Button)findViewById(R.id.bon);
        btnOff = (Button)findViewById(R.id.boff);
        // ボタンをクリックしたときにbtnOnOffClickListenerを呼ぶようにトリガーをセット
        btnOn.setOnClickListener(btnOnOffClickListener);
        btnOff.setOnClickListener(btnOnOffClickListener);
        txtDevices = (TextView)findViewById(R.id.Devices);
        fabExit = (FloatingActionButton)findViewById(R.id.ExitBtn);
        fabExit.setOnClickListener(btnOnOffClickListener);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //オプションメニューを作成（設定）
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
    @Override
    protected  void onResume() {
        super.onResume();
        // 設定を取り込む
        getPrefarence();
        //現在の状態を取得
        OnOffRequest("Status");
    }
    //ボタンを押されたときの処理
    View.OnClickListener btnOnOffClickListener = new View.OnClickListener(){
        @Override
        public void onClick(View ViewButton) {
            String onoff;
            if(ViewButton == fabExit ) {
                Toast.makeText(getBaseContext(), getString(R.string.ending), Toast.LENGTH_SHORT).show();
                finish();
                android.os.Process.killProcess(android.os.Process.myPid());
            }else {
                if (ViewButton == btnOn) {
                    onoff = "ON";
                } else {
                    onoff = "OFF";
                }
                Toast.makeText(MainActivity.this, getString(R.string.requests) + onoff, Toast.LENGTH_LONG).show();
                OnOffRequest(onoff);
            }
         }
    };
    //ESPにリクエストを送る
    void OnOffRequest(String onoff){
        btnOn.setEnabled(true);
        btnOff.setEnabled(true);
        //非同期タスクの生成
        TaskEsp taskEsp = new TaskEsp(TargetIP);
        //非同期処理を実行
        taskEsp.execute(onoff);
    }
    //非同期処理定義
    private class TaskEsp extends AsyncTask<String, Void, String> {
        String server;
        //コンストラクタ
        TaskEsp(String server){
            super();
            this.server = server;
        }
        //バックグラウンドで処理を実行
        @Override
        protected String doInBackground(String... params) {
            String val = params[0];
            final String p = server+"?pin="+val;
         //   txtStatus.setText(p);
            String serverResponse = "";
            //　リクエストを投げる
            try {
                HttpURLConnection httpURLConnection = (HttpURLConnection)(new URL(p).openConnection());
                if(httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    InputStream inputStream = null;
                    inputStream = httpURLConnection.getInputStream();
                    BufferedReader bufferedReader =  new BufferedReader(new InputStreamReader(inputStream));
                    serverResponse = bufferedReader.readLine();
                    inputStream.close();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
                serverResponse = e.getMessage();
            } catch (IOException e) {
                e.printStackTrace();
                serverResponse = e.getMessage();
            } catch (Exception  e) {
                e.printStackTrace();
                serverResponse = e.getMessage();
            }
            //表示メッセージを返す
            return serverResponse;
        }
        @Override
        protected void onPostExecute(String s) {
            if(s.equals("ON")) {
                btnOff.setEnabled(true);
                btnOff.setBackgroundColor(Color.GRAY);
                btnOn.setBackgroundColor(Color.RED);
            }else if(s.equals("OFF")) {
                btnOn.setEnabled(true);
                btnOn.setBackgroundColor(Color.GRAY);
                btnOff.setBackgroundColor(Color.GREEN);
            }else{
                txtStatus.setText(getResources().getString(R.string.unConnect));
            }

        }
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //メニューを選択されたときの処理
        Toast.makeText(MainActivity.this, "menu", Toast.LENGTH_LONG).show();
        switch (item.getItemId()) {
            case R.id.action_btn:
                // 設定画面を起動する
                startActivity(new Intent(this, SettingsActivity.class));
                return true;
            case R.id.action_exit:
                Toast.makeText(getBaseContext() ,getString(R.string.ending),Toast.LENGTH_SHORT).show();
                finish();
                android.os.Process.killProcess(android.os.Process.myPid());
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    //データ読み出し
    void  getPrefarence() {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        TargetIP = sp.getString("ip", "");
        TargetDevice = sp.getString("devicename", "");
        if(TargetIP.length()==0){
            TargetIP=getResources().getString(R.string.summary_ip);
        }
        if(TargetDevice.length()==0){
            TargetDevice=getResources().getString(R.string.summary_name);
        }
        txtDevices.setText(TargetDevice);
    }
}