package tech.starwin.utils.context_utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import java.io.Serializable;

import tech.starwin.R;

/**
 * Created by SiKang on 2018/9/16.
 */
public class IntentHolder {
    private Intent intent;
    /**
     * 发起跳转的Context
     */
    private Context context;

    private IntentHolder(Context from, Intent intent) {
        this.intent = intent;
        this.context = from;
    }

    /**
     * 打开Activity
     */
    public void start() {
        if (context == null) {
            return;
        }
        context.startActivity(intent);
        if (context instanceof Activity) {
            ((Activity) context).overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
        }
    }

    /**
     * 在新的Task种打开Activity
     */
    public void startWithNewTask() {
        if (context == null)
            return;
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public Intent getIntent() {
        return intent;
    }

    public static class Builder {
        private Intent intent;
        private Context fromContext;

        public Builder() {

        }

        public <C extends Activity> Builder(Context from, Class<C> target) {
            this.fromContext = from;
            intent = new Intent(fromContext, target);
        }

        public Builder(Context from, String action) {
            this.fromContext = from;
            intent = new Intent(action);
        }

        public Builder put(String key, String value) {
            intent.putExtra(key, value);
            return this;
        }

        public Builder put(String key, int value) {
            intent.putExtra(key, value);
            return this;
        }

        public Builder put(String key, float value) {
            intent.putExtra(key, value);
            return this;
        }

        public Builder put(String key, double value) {
            intent.putExtra(key, value);
            return this;
        }

        public Builder put(String key, boolean value) {
            intent.putExtra(key, value);
            return this;
        }

        public Builder put(String key, Serializable obj) {
            intent.putExtra(key, obj);
            return this;
        }

        public IntentHolder build() {
            return new IntentHolder(fromContext, intent);
        }

        public Intent toIntent() {
            return intent;
        }

        public Bundle toBundle() {
            return intent.getExtras();
        }
    }

}

