package cloud.hmml.mmw;

import android.app.Activity;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import java.text.DateFormat;
import java.util.Date;

/**
 * The configuration screen for the {@link WeatherDispWidget WeatherDispWidget} AppWidget.
 */
public class WeatherDispWidgetConfigureActivity extends Activity {
    ConfigManager conf = null;
    int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
    private boolean isFinishRequested = false;
    static int ACTIVITY_RET_THEME_PICKED = 1;

    private Button mBtnLocChange;
    private CheckBox mChkAutoLocation;
    private RadioButton mRadioTempUnit_F;
    private RadioButton mRadioTempUnit_C;
    private TextView mTxtLocationName;
    private TextView mTxtUpdatedAt;
    private Button mBtnFetch;
    private TextView mTxtReportedAt;
    private Button mBtnThemeChange;
    private ImageView mThemeImage;
    private TextView mThemeName;
    private TextView mThemeAuthor;
    private TextView mThemeDesc;

    View.OnClickListener mOnClickListener = new View.OnClickListener() {
        public void onClick(View v) {
            final Context context = WeatherDispWidgetConfigureActivity.this;
            Log.d("conf", "OK btn is clicked. Finishing config screen.");

            // When the button is clicked, store the string locally
            conf.saveTempUnit(mRadioTempUnit_F.isChecked() ? "f" : "c");
            conf.saveAutoLocation(mChkAutoLocation.isChecked());

            if (conf.loadConfigAt() == null) {
                Log.d("conf", "First config call. Trying to request permission.");
                if (!conf.checkPermission()) {
                    isFinishRequested = true;
                    return;
                }
            }

            finishAndApply();
        }
    };

    public void finishAndApply() {
        final Context context = this;

        if (conf.loadConfigAt() == null) {
            Log.d("conf", "First config, Try to update weather.");
            conf.updateWeather();
        }

        conf.saveConfigAt();
        // It is the responsibility of the configuration activity to update the app widget
        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
        WeatherDispWidget.updateAppWidget(context, appWidgetManager, mAppWidgetId);

        // Make sure we pass back the original appWidgetId
        Intent resultValue = new Intent();
        resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
        setResult(RESULT_OK, resultValue);
        finish();
    }

    public WeatherDispWidgetConfigureActivity() {
        super();
    }

    public void applyConfToScreen() {
        mChkAutoLocation.setChecked(conf.loadAutoLocation());
        mRadioTempUnit_F.setChecked(conf.isTempUnitF());
        if (mChkAutoLocation.isChecked()) {
            mBtnLocChange.setVisibility(View.GONE);
        } else {
            mBtnLocChange.setVisibility(View.VISIBLE);
        }
        mTxtLocationName.setText(conf.loadLocationLabel());
        Date upd = conf.loadUpdatedAt();
        if (upd != null)
            mTxtUpdatedAt.setText(DateFormat.getDateTimeInstance().format(upd));
        upd = conf.loadReportedAt();
        if (upd != null)
            mTxtReportedAt.setText(DateFormat.getDateTimeInstance().format(upd));

        Theme theme = conf.getTheme();
        mThemeImage.setImageBitmap(theme.getIconBitmap(Theme.W_CLEAR_D));
        if (theme.day_frame != null && theme.day_frame.equals("builtin/white")) {
            mThemeImage.setBackground(ContextCompat.getDrawable(this, R.drawable.day_frame_white));
        } else {
            mThemeImage.setBackground(ContextCompat.getDrawable(this, R.drawable.day_frame_black));
        }
        mThemeName.setText(theme.getName());
        mThemeAuthor.setText(theme.getAuthor());

        final Uri uri = theme.getUri();
        if (uri != null) {
            mThemeAuthor.setTextColor(Color.BLUE);
            mThemeAuthor.setPaintFlags(mThemeAuthor.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
            mThemeAuthor.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent i = new Intent(Intent.ACTION_VIEW, uri);
                    v.getContext().startActivity(i);
                }
            });
        }
        mThemeDesc.setText(theme.getShortDesc());
    }

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        // Set the result to CANCELED.  This will cause the widget host to cancel
        // out of the widget placement if the user presses the back button.
        setResult(RESULT_CANCELED);

        // Find the widget id from the intent.
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras != null) {
            mAppWidgetId = extras.getInt(
                    AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
        }

        // If this activity was started with an intent without an app widget ID, finish with an error.
        if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
            finish();
            return;
        }

        setContentView(R.layout.weather_disp_widget_configure);
        findViewById(R.id.btn_conf_ok).setOnClickListener(mOnClickListener);

        conf = new ConfigManager(this, mAppWidgetId);
        mBtnLocChange = (Button) findViewById(R.id.btn_location_change);
        mChkAutoLocation = (CheckBox) findViewById(R.id.chk_auto_location);
        mRadioTempUnit_C = (RadioButton) findViewById(R.id.temp_unit_c);
        mRadioTempUnit_F = (RadioButton) findViewById(R.id.temp_unit_f);
        mTxtLocationName = (TextView) findViewById(R.id.txt_location_name);
        mTxtUpdatedAt = (TextView) findViewById(R.id.txt_last_update);
        mTxtReportedAt = (TextView) findViewById(R.id.txt_last_forecast);
        mBtnFetch = (Button) findViewById(R.id.btn_fetch);
        mBtnThemeChange = (Button) findViewById(R.id.btn_theme_change);
        mThemeImage = (ImageView) findViewById(R.id.theme_cur_image);
        mThemeName = (TextView) findViewById(R.id.theme_cur_name);
        mThemeAuthor = (TextView) findViewById(R.id.theme_cur_author);
        mThemeDesc = (TextView) findViewById(R.id.theme_cur_desc);

        mChkAutoLocation.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mBtnLocChange.setVisibility(View.GONE);
                } else {
                    mBtnLocChange.setVisibility(View.VISIBLE);
                }
            }
        });

        mBtnFetch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                conf.updateWeather();           }
        });
        mBtnLocChange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(conf.getContext(), "手動設定は現在未実装です。もうしばらくお待ちください。", Toast.LENGTH_SHORT).show(); // TODO: impl
            }
        });

        mBtnThemeChange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(WeatherDispWidgetConfigureActivity.this, ThemePickerActivity.class);
                startActivityForResult(i, ACTIVITY_RET_THEME_PICKED);
            }
        });

        applyConfToScreen();
    }

    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        Log.d("conf", "Request permission result is called.");
        if (grantResults.length == 0)
            return;
        if (requestCode == ConfigManager.REQUEST_PERMISSION_OK && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            conf.updateLocation();
            if (isFinishRequested)
                finishAndApply();
        } else {
            Log.e("conf", "Getting Location permission has been rejected.");
            Toast.makeText(this, R.string.location_perm_rejected , Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onDestroy() {
        if (this.conf != null) {
            conf.onDestroy();
            this.conf = null;
        }
        super.onDestroy();
    }

    @Override
    public void onResume() {
        super.onResume();
        this.applyConfToScreen();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == ACTIVITY_RET_THEME_PICKED) {
            Log.d("conf", "theme pick result: " + resultCode  + " (expected: " + RESULT_OK +")");
            if (resultCode != RESULT_OK)
                return;
            int type = data.getIntExtra("TYPE", -1);
            int id = data.getIntExtra("ID", -1);
            Log.d("conf", "theme change has been requested: "+type+"/"+id);
            if (type == -1 || id == -1)
                return;
            conf.setTheme(type, id);
            applyConfToScreen();
        }
    }
}

