package ai.pai.client.activity;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.android.common.executors.ThreadExecutor;
import com.android.common.utils.JSONParseUtils;
import com.android.common.utils.LogHelper;
import com.android.views.progressbar.ProgressWheel;

import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import ai.pai.client.R;
import ai.pai.client.adapter.FullScreenPhotoPageAdapter;
import ai.pai.client.beans.GroupPhotoItem;
import ai.pai.client.db.Preferences;
import ai.pai.client.utils.HttpPostTask;
import ai.pai.client.utils.UrlContainer;
import ai.pai.client.views.HackyViewPager;

public class PaidPhotoActivity extends BaseActivity implements View.OnClickListener, ViewPager.OnPageChangeListener {


    private ArrayList<GroupPhotoItem> photoList;
    private GroupPhotoItem currentPhotoItem;
    private ProgressWheel spinner;
    private SavePhotoTask savePhotoTask;
    private HttpPostTask getPhotoTask;
    private boolean isPhotoInfoFetched;
    private HackyViewPager photoPager;
    private FullScreenPhotoPageAdapter photoPageAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_full_screen);

        photoList = new ArrayList<GroupPhotoItem>();
        currentPhotoItem = (GroupPhotoItem) getIntent().getSerializableExtra("photo_item");
        photoList.add(currentPhotoItem);
        photoPager = (HackyViewPager) findViewById(R.id.pager_photo);
        spinner = (ProgressWheel)findViewById(R.id.wheel_wait_http);
        photoPageAdapter = new FullScreenPhotoPageAdapter(this, photoList,photoPager);
        photoPager.setAdapter(photoPageAdapter);
        photoPager.addOnPageChangeListener(this);
        photoPager.setCurrentItem(photoList.indexOf(currentPhotoItem));
        findViewById(R.id.btn_back_full_screen).setOnClickListener(this);
        findViewById(R.id.btn_download_full_screen).setOnClickListener(this);

        doGetPhotoTask();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_back_full_screen:
                finish();
                break;
            case R.id.btn_download_full_screen:
                if(currentPhotoItem.photoFrom==1 && TextUtils.isEmpty(currentPhotoItem.mediumPhotoUrl) && TextUtils.isEmpty(currentPhotoItem.rawPhotoUrl)&&isPhotoInfoFetched){
                    Toast.makeText(this,R.string.photo_need_buy,Toast.LENGTH_SHORT).show();
                    return;
                }
                if(!isPhotoInfoFetched && TextUtils.isEmpty(currentPhotoItem.mediumPhotoUrl) && TextUtils.isEmpty(currentPhotoItem.rawPhotoUrl)){
                    doGetPhotoTask();
                    Toast.makeText(this,R.string.photo_info_processing,Toast.LENGTH_SHORT).show();
                    return;
                }

                if(savePhotoTask!=null && savePhotoTask.getStatus()== AsyncTask.Status.RUNNING){
                    savePhotoTask.cancel(true);
                }
                savePhotoTask = new SavePhotoTask(this);
                String photoUrl = currentPhotoItem.rawPhotoUrl;
                if(TextUtils.isEmpty(photoUrl)){
                    photoUrl = currentPhotoItem.mediumPhotoUrl;
                }
                if(TextUtils.isEmpty(photoUrl)){
                    photoUrl = currentPhotoItem.photoUrl;
                }
                savePhotoTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(),photoUrl);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(savePhotoTask!=null && savePhotoTask.getStatus()== AsyncTask.Status.RUNNING){
            savePhotoTask.cancel(true);
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        currentPhotoItem = photoList.get(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    private void doGetPhotoTask() {
        if(!TextUtils.isEmpty(currentPhotoItem.mediumPhotoUrl)&&!TextUtils.isEmpty(currentPhotoItem.rawPhotoUrl)){
            isPhotoInfoFetched = true;
            return;
        }
        if (getPhotoTask != null && getPhotoTask.getStatus() == AsyncTask.Status.RUNNING) {
            getPhotoTask.cancel(true);
        }
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("user_id", Preferences.getInstance(this).getUserId());
        params.put("photo_id", currentPhotoItem.photoId);
        getPhotoTask = new HttpPostTask(this, params) {
            @Override
            protected boolean parseResponse(Context context, String response) {
                try {
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    if (status == 200) {
                        LogHelper.d(TAG, " getPhotoTask parseResponse status ok");
                        JSONObject data = json.getJSONObject("data");
                        JSONObject porder = data.getJSONObject("porder");
                        if(porder.has("r_photo_url")){
                            String rPhotoUrl = JSONParseUtils.getJSONString(porder.getString("r_photo_url"));
                            currentPhotoItem.rawPhotoUrl = rPhotoUrl;                        }
                        if(porder.has("m_photo_url")){
                            String mPhotoUrl = JSONParseUtils.getJSONString(porder.getString("m_photo_url"));
                            currentPhotoItem.mediumPhotoUrl = mPhotoUrl;
                        }
                        return true;
                    }
                } catch (Exception e) {
                    LogHelper.d(TAG, " getPhotoTask parseResponse error :" + e);
                }
                return false;
            }

            @Override
            protected void onPostFail(Context context) {
                super.onPostFail(context);
            }

            @Override
            protected void onPostSuccess(Context context) {
                super.onPostSuccess(context);
                isPhotoInfoFetched = true;
                photoPageAdapter = new FullScreenPhotoPageAdapter(PaidPhotoActivity.this, photoList,photoPager);
                photoPager.setAdapter(photoPageAdapter);
            }

        };
        getPhotoTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), UrlContainer.BOUGHT_PHOTO_URL);
    }

     class SavePhotoTask extends AsyncTask<String, Integer, Boolean> {

        private Context context;
        private File file;
        private String name;

        public SavePhotoTask(Context context) {
            this.context = context;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Toast.makeText(context, R.string.save_photo_processing, Toast.LENGTH_SHORT).show();
            spinner.setVisibility(View.VISIBLE);
            spinner.startSpinning();        }

        @Override
        protected Boolean doInBackground(String... params) {
            String  path = params[0];
            FileOutputStream fOut = null;
            Bitmap bitmap = null;
            HttpURLConnection conn = null;
            InputStream inStream = null;
            try {
                URL url = new URL(path);
                conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(5 * 1000);
                conn.setRequestMethod("GET");
                inStream = conn.getInputStream();
                if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
                    bitmap = BitmapFactory.decodeStream(inStream);
                }
                File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
                name = System.currentTimeMillis() + ".jpg";
                file = new File(dir, name);
                fOut = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
                fOut.flush();
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try{
                    inStream.close();
                    conn.disconnect();
                    fOut.close();
                    bitmap.recycle();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            spinner.stopSpinning();
            spinner.setVisibility(View.GONE);
            if (result) {
                Toast.makeText(context, R.string.save_photo_success, Toast.LENGTH_SHORT).show();
                try {
                    MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getPath(), name, name);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(context, R.string.save_photo_fail, Toast.LENGTH_SHORT).show();
            }
        }
    }
}
