package com.meerkat.laura.fakescannerapp;


import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import meerkat.pollingstation.ScannerClientAPI;
import meerkat.protobuf.PollingStation;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLDecoder;

import static com.meerkat.laura.fakescannerapp.R.xml.preferences;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    SharedPreferences sharedPref;

    Button scanBtn;
    TextView formatTxt, contentTxt, responseTxt;
    ScannerClientAPI scannerClientAPI;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.options_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.action_settings:
                Intent i = new Intent(this, SettingsActivity.class);
                startActivity(i);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    void setNewScannerClientAPI(SharedPreferences sharedPref) {
        String pscUrlString = sharedPref.getString(SettingsActivity.PSC_URL, "");
        scannerClientAPI = new ScannerClientAPI(pscUrlString);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        PreferenceManager.setDefaultValues(this, preferences, false);
        sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
        sharedPref.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {
            @Override
            public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
                if (s.equals(SettingsActivity.PSC_URL))
                    setNewScannerClientAPI(sharedPreferences);
            }
        });

        scanBtn = (Button)findViewById(R.id.scan_button);
        formatTxt = (TextView)findViewById(R.id.scan_format);
        contentTxt = (TextView)findViewById(R.id.scan_content);
        responseTxt = (TextView)findViewById(R.id.server_response);

        setNewScannerClientAPI(sharedPref);
        scanBtn.setOnClickListener(this);
    }

    public void onClick(View v){
        if(v.getId()==R.id.scan_button){
            IntentIntegrator scanIntegrator = new IntentIntegrator(this);
            formatTxt.setText("Initiating scan...");
            scanIntegrator.initiateScan();
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
        if (scanningResult != null) {
            String scanContent = scanningResult.getContents();
            byte[] rawBytes = scanningResult.getRawBytes();
            String scanFormat = scanningResult.getFormatName();
            formatTxt.setText("FORMAT: " + scanFormat);
            contentTxt.setText("CONTENT: " + scanContent + "sending data to server...");
//            sendPost(rawBytes);
            sendPost(scanContent);
        } else{
            Toast toast = Toast.makeText(getApplicationContext(),
                    "No scan data received!", Toast.LENGTH_SHORT);
            toast.show();
        }
    }

//    public void sendPost(byte[] body) {
public void sendPost(String scanContent) {

        try {
            PollingStation.ScannedData scannedData = PollingStation.ScannedData.parseFrom(Base64.decode(scanContent.getBytes(), Base64.DEFAULT));
    //
    //        PollingStation.ScannedData scannedData = PollingStation.ScannedData.newBuilder()
    //                .setChannel(ByteString.copyFrom(body))
    //                .build();

            if (scannerClientAPI.sendScan(scannedData)) {
                Log.i("MainActivity", "post submitted to API.");
            } else {
                Log.e("MainActivity", "Unable to submit post to API.");
            }
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }
    }

    public void showResponse(String response) {
        responseTxt.setText(response);
    }

}
