package ai.pai.client.activity;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.UnderlineSpan;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.common.executors.ThreadExecutor;
import com.android.common.utils.DeviceUtils;
import com.android.common.utils.JSONParseUtils;
import com.android.views.indicators.Indicator;
import com.android.views.indicators.IndicatorViewPager;
import com.android.views.progressbar.ProgressWheel;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import ai.pai.client.R;
import ai.pai.client.db.Preferences;
import ai.pai.client.utils.HttpPostTask;
import ai.pai.client.utils.UrlContainer;

public class GuideActivity extends FragmentActivity{
	private IndicatorViewPager indicatorViewPager;
    private SHARE_MEDIA platform = SHARE_MEDIA.WEIXIN;
    private UMShareAPI umShareAPI;
    private boolean isAuthComplete;
    private ProgressWheel wheel;

    private String wx_uid;
    private String sex;
    private String nickname;
    private String headimgurl;
    private String country;
    private String province;
    private String city;
    private String unionId;

    private HttpPostTask LoginTask;
    private HttpPostTask guestLoginTask;

    @Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.activity_guide);
        wheel = (ProgressWheel)findViewById(R.id.wheel_wait_http);
		ViewPager viewPager = (ViewPager) findViewById(R.id.guide_viewPager);
		Indicator indicator = (Indicator) findViewById(R.id.guide_indicator);
		indicatorViewPager = new IndicatorViewPager(indicator, viewPager);
		indicatorViewPager.setAdapter(adapter);
        TextView guestTextView = (TextView)findViewById(R.id.tv_login_guest);
        SpannableString content = new SpannableString(getString(R.string.guest_login));
        content.setSpan(new UnderlineSpan(),0, content.length(), 0);
        guestTextView.setText(content);
        findViewById(R.id.btn_login).setOnClickListener(new View.OnClickListener(){
			@Override
			public void onClick(View v) {
                umShareAPI.doOauthVerify(GuideActivity.this, platform, umAuthListener);
			}
		});
        if(getIntent().getBooleanExtra("showGuest",false)){
            findViewById(R.id.btn_login_guest).setVisibility(View.VISIBLE);
        }
        findViewById(R.id.btn_login_guest).setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                clickGuestLogin();
            }
        });
        umShareAPI = UMShareAPI.get(this);
	}

    private void clickGuestLogin() {
        if (guestLoginTask != null && guestLoginTask.getStatus() == AsyncTask.Status.RUNNING) {
            guestLoginTask.cancel(true);
        }
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("uuid", DeviceUtils.getUUID(this));
        guestLoginTask = new HttpPostTask(this, params) {

            private String toastMsg;

            @Override
            protected boolean parseResponse(Context context, String response) {
                try{
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    toastMsg = JSONParseUtils.getJSONString(json.getString("message"));
                    if(status == 200){
                        JSONObject info = json.getJSONObject("data");
                        String user_id = JSONParseUtils.getJSONString(info.getString("user_id"));
                        String userName = JSONParseUtils.getJSONString(info.getString("username"));
                        String nick_name = JSONParseUtils.getJSONString(info.getString("nickname"));
                        Preferences.getInstance(context).setUserId(user_id);
                        Preferences.getInstance(context).setUserName(userName);
                        Preferences.getInstance(context).setNickName(nick_name);
                        return true;
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                return false;
            }

            @Override
            protected void onPostSuccess(Context context) {
                wheel.stopSpinning();
                wheel.setVisibility(View.GONE);
                if(TextUtils.isEmpty(toastMsg)){
                    toastMsg = getString(R.string.login_success);
                }
                Preferences.getInstance(context).setGuestLogin(true);
                Toast.makeText(context,toastMsg, Toast.LENGTH_LONG).show();
                setResult(RESULT_OK);
                startActivity(new Intent(GuideActivity.this,MainActivity.class));
                finish();
            }

            @Override
            protected void onPostFail(Context context) {
                wheel.stopSpinning();
                wheel.setVisibility(View.GONE);
                if(TextUtils.isEmpty(toastMsg)){
                    toastMsg = getString(R.string.login_fail);
                }
                Toast.makeText(context,toastMsg, Toast.LENGTH_LONG).show();
            }

        };
        guestLoginTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), UrlContainer.GUEST_LOGIN_URL);
    }

    private IndicatorViewPager.IndicatorPagerAdapter adapter = new IndicatorViewPager.IndicatorViewPagerAdapter() {
		private int[] images = { R.drawable.p1, R.drawable.p2, R.drawable.p3 };

		@Override
		public View getViewForTab(int position, View convertView, ViewGroup container) {
		    ImageView img = new ImageView(GuideActivity.this);
            img.setImageResource(R.drawable.tab_selector);
            img.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
            img.setPadding(3,3,3,3);
			return img;
		}

		@Override
		public View getViewForPage(int position, View convertView, ViewGroup container) {
			if (convertView == null) {
				convertView = new View(getApplicationContext());
				convertView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
			}
			convertView.setBackgroundResource(images[position]);
			return convertView;
		}

		@Override
		public int getCount() {
			return images.length;
		}
	};

    private UMAuthListener umAuthListener = new UMAuthListener() {
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            if(!isAuthComplete){
                Toast.makeText( getApplicationContext(), R.string.weixin_auth_success, Toast.LENGTH_SHORT).show();
                umShareAPI.getPlatformInfo(GuideActivity.this,platform,this);
                isAuthComplete = true;
            }else{
                wx_uid = data.get("openid");
                sex = data.get("sex");
                nickname = data.get("nickname");
                headimgurl = data.get("headimgurl");
                country = data.get("country");
                province = data.get("province");
                city = data.get("city");
                unionId = data.get("unionid");
                submitInfo();
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            Toast.makeText( getApplicationContext(), R.string.weixin_auth_fail, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            Toast.makeText( getApplicationContext(), R.string.weixin_auth_fail, Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        umShareAPI.onActivityResult(requestCode,resultCode,data);
    }

    private void submitInfo(){
        if(LoginTask!=null && LoginTask.getStatus() == AsyncTask.Status.RUNNING){
            return;
        }
        HashMap<String,String> params = new HashMap<String,String>();
        params.put("user_id", Preferences.getInstance(this).getUserId());
        params.put("wx_uid",wx_uid);
        params.put("sex",sex);
        params.put("nickname",nickname);
        params.put("headimgurl",headimgurl);
        params.put("country",country);
        params.put("province",province);
        params.put("city",city);
        params.put("unionid",unionId);

        LoginTask= new HttpPostTask(this,params){

            private String toastMsg;
            @Override
            protected boolean parseResponse(Context context, String response) {
                try{
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    toastMsg = JSONParseUtils.getJSONString(json.getString("message"));
                    if(status == 200){
                        JSONObject info = json.getJSONObject("data");
                        String user_id = JSONParseUtils.getJSONString(info.getString("user_id"));
                        String userName = JSONParseUtils.getJSONString(info.getString("username"));
                        String nick_name = JSONParseUtils.getJSONString(info.getString("nickname"));
                        Preferences.getInstance(context).setUserId(user_id);
                        Preferences.getInstance(context).setUserName(userName);
                        Preferences.getInstance(context).setNickName(nick_name);
                        Preferences.getInstance(context).setUserAvatar(headimgurl);
                        return true;
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                return false;
            }

            @Override
            protected void onPreExecute() {
                wheel.setVisibility(View.VISIBLE);
                wheel.startSpinning();
            }

            @Override
            protected void onPostSuccess(Context context) {
                wheel.stopSpinning();
                wheel.setVisibility(View.GONE);
                if(TextUtils.isEmpty(toastMsg)){
                    toastMsg = getString(R.string.login_success);
                }
                Preferences.getInstance(context).setGuestLogin(false);
                Toast.makeText(context,toastMsg, Toast.LENGTH_LONG).show();
                setResult(RESULT_OK);
                startActivity(new Intent(GuideActivity.this,MainActivity.class));
                finish();
            }

            @Override
            protected void onPostFail(Context context) {
                wheel.stopSpinning();
                wheel.setVisibility(View.GONE);
                if(TextUtils.isEmpty(toastMsg)){
                    toastMsg = getString(R.string.login_fail);
                }
                Toast.makeText(context,toastMsg, Toast.LENGTH_LONG).show();
            }
        };
        LoginTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), UrlContainer.WX_AUTHORIZE_URL);
    }

}
