package ai.pai.client.activity;

import android.content.Context;
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.LogHelper;
import com.android.views.progressbar.ProgressWheel;
import com.umeng.analytics.MobclickAgent;

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 ai.pai.client.BuildConfig;
import ai.pai.client.R;
import ai.pai.client.adapter.FullScreenPhotoPageAdapter;
import ai.pai.client.beans.GroupPhotoItem;
import ai.pai.client.utils.UmengEvent;
import ai.pai.client.views.HackyViewPager;

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


    private ArrayList<GroupPhotoItem> photoList;
    private GroupPhotoItem currentPhotoItem;
    private ProgressWheel spinner;
    private SavePhotoTask savePhotoTask;

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

        photoList = (ArrayList<GroupPhotoItem>) getIntent().getSerializableExtra("list");
        currentPhotoItem = (GroupPhotoItem) getIntent().getSerializableExtra("photo_item");
        HackyViewPager photoPager = (HackyViewPager) findViewById(R.id.pager_photo);
        spinner = (ProgressWheel)findViewById(R.id.wheel_wait_http);
        FullScreenPhotoPageAdapter 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);
    }

    @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:
                MobclickAgent.onEvent(this, UmengEvent.fullscreen_download_btn_click);
                if(currentPhotoItem.photoFrom==1 && TextUtils.isEmpty(currentPhotoItem.mediumPhotoUrl) && TextUtils.isEmpty(currentPhotoItem.rawPhotoUrl)){
                    Toast.makeText(this,R.string.photo_need_buy,Toast.LENGTH_SHORT).show();
                    return;
                }
                if(savePhotoTask!=null && savePhotoTask.getStatus()== AsyncTask.Status.RUNNING){
                    savePhotoTask.cancel(true);
                }
                savePhotoTask = new SavePhotoTask(this);
                savePhotoTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(),
                        currentPhotoItem.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) {

    }

     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;
            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){
                    File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
                    name = System.currentTimeMillis() + ".jpg";
                    file = new File(dir, name);
                    fOut = new FileOutputStream(file);
                    byte[] buffer = new byte[2048];
                    int len ;
                    while((len=inStream.read(buffer))!=-1){
                        fOut.write(buffer,0,len);
                        fOut.flush();
                    }
                    fOut.flush();
                    if(BuildConfig.isDevMode){
                        LogHelper.dfile("czy","保存照片到本地，图片链接地址为"+path);
                        LogHelper.dfile("czy","保存照片到本地，图片保存至"+file.getAbsolutePath()+"图片大小为"+file.length()+"字节\n\n");
                    }
                }
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try{
                    inStream.close();
                    conn.disconnect();
                    fOut.close();
                }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();
            }
        }
    }
}
