package com.example.maheshraja.mycampus.Activity;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import com.example.maheshraja.mycampus.R;
import com.example.maheshraja.mycampus.asynctask.SearchJobAsynTask;
import com.example.maheshraja.mycampus.daos.JobportalDAo;
import com.example.maheshraja.mycampus.daos.UserDAO;
import com.example.maheshraja.mycampus.database.DBHandler;
import com.example.maheshraja.mycampus.dtos.DTO;
import com.example.maheshraja.mycampus.dtos.JobPortalDTO;
import com.example.maheshraja.mycampus.dtos.UserDTO;
import com.example.maheshraja.mycampus.listener.AsyncTaskCompleteListener;
import com.example.maheshraja.mycampus.utility.MyConstants;
import com.example.maheshraja.mycampus.utility.Utility;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by lenovo on 30-07-2016.
 */
public class JobportalForm extends  BaseFragment {
    private Context context;
EditText userNameEdt;
    EditText mobileNoEdt;
    EditText emailIdEdt;
    EditText KeySkillEdt;
EditText reg_resume;
    EditText reg_sscper;
    EditText reg_inter;
    EditText reg_btech;
    Button btnSubmit;
    EditText preferedlocation;
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        context = mActivity;
        View rootView = inflater.inflate(R.layout.fragemt_jobportalform, container, false);

        userNameEdt = (EditText)rootView. findViewById(R.id.reg_name);
        mobileNoEdt = (EditText)rootView. findViewById(R.id.reg_mobile);
        emailIdEdt = (EditText)rootView. findViewById(R.id.reg_email);
        KeySkillEdt = (EditText)rootView. findViewById(R.id.reg_keyskills);
        reg_resume = (EditText)rootView. findViewById(R.id.reg_resume);
        reg_sscper = (EditText)rootView. findViewById(R.id.reg_sscper);
        reg_inter=(EditText)rootView. findViewById(R.id.reg_inter);
        reg_btech=(EditText)rootView. findViewById(R.id.reg_btech);
        preferedlocation=(EditText)rootView. findViewById(R.id.reg_location);
        btnSubmit = (Button)rootView. findViewById(R.id.reg_submit);
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String validation = validateFields();
                if (validation == null) {

                        if (Utility.networkAvailability(context)) {
//                        showProgress();
                            registrationProcess();
//                            loginProcess();
                            //saveData(getUserData());;
                        } else {
                            Utility.showAlert(context, null, getString(R.string.check_connection));
                        }

                } else {
                    Utility.showAlert(context, "Alert", validation);
                }
                //uploadImage();
            }
        });



        return  rootView;
    }

    private boolean isTextEmpty(EditText editText) {
        if (!editText.getText().toString().trim().isEmpty())
            return false;
        else
            return true;
    }
    private String getText(EditText editText) {
        return editText.getText().toString().trim();
    }

    private String validateFields() {
        if (isTextEmpty(userNameEdt)) {
            return "Enter your name";
        }

        if (isTextEmpty(mobileNoEdt)) {
            return "Enter mobile number";
        }

        if (mobileNoEdt.getText().toString().trim().length() <= 9) {
            return "Enter valid mobile number";
        }

        if (isTextEmpty(emailIdEdt)) {
            return "Enter mail ID";
        }

        if(!isValidEmailAddress(getText(emailIdEdt))){
            return "Enter valid mail ID";
        }

        if (isTextEmpty(KeySkillEdt)) {
            return "Enter Keyskill";
        }



        if (isTextEmpty(reg_resume)) {
            return "Enter Resume Headline";
        }



        if (isTextEmpty(reg_sscper)) {
            return "Enter SSC Percentage";
        }

        /*if (isTextEmpty(uidEdt)) {
            return "Enter UID";
        }*/

        if (isTextEmpty(reg_inter)) {
            return "Enter Inter Percentage";
        }

        /*if (isTextEmpty(locationEdt)) {
            return "Enter your location";
        }*/

        if (isTextEmpty(reg_btech)) {
            return "Enter BTECH Percentage";
        }

        if (isTextEmpty(preferedlocation)) {
            return "Enter Loctaion";
        }

        return null;
    }

    public boolean isValidEmailAddress(String email) {
        String ePattern = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$";
        java.util.regex.Pattern p = java.util.regex.Pattern.compile(ePattern);
        java.util.regex.Matcher m = p.matcher(email);
        return m.matches();
    }
    private void registrationProcess() {

        UserDTO localObject = (UserDTO) UserDAO.getInstance().getRecords(DBHandler.getInstance(this.mActivity).getDBObject(0)).get(0);

        JobPortalDTO dto = (JobPortalDTO) getUserData();

        JSONObject reqJson = new JSONObject();

        try {
            reqJson.put("userName", dto.getUserName());
            System.out.println("userName" + dto.getUserName());
            reqJson.put("mobileNumber", dto.getMobileNumber());
            System.out.println("mobileNumber" + dto.getMobileNumber());
            reqJson.put("preferedLocation", dto.getPreferedLocation());
            System.out.println("preferedLocation" + dto.getPreferedLocation());
            reqJson.put("emailAddress", dto.getEmailAddress());
            System.out.println("emailAddress" + dto.getEmailAddress());
            reqJson.put("resumeHeadline", dto.getResumeHeadline());
            System.out.println("resumeHeadline" + dto.getResumeHeadline());
            reqJson.put("keySkills", dto.getKeySkills());
            System.out.println("keySkills" + dto.getKeySkills());
            reqJson.put("SSCPercentage", dto.getSSCPercentage());
            System.out.println("SSCPercentage" + dto.getSSCPercentage());
            reqJson.put("interPercentage", dto.getInterPercentage());
            System.out.println("interPercentage" + dto.getInterPercentage());
            reqJson.put("btechPercentage", dto.getBtechPercentage());
            System.out.println("btechPercentage" + dto.getBtechPercentage());
            reqJson.put("campus_emailid", dto.getCampus_emailid());
            System.out.println("campus_emailid" + localObject.getEmailId());
        } catch (JSONException e) {
            e.printStackTrace();
        }catch (Exception e){

        }

        SearchJobAsynTask loginAsync = new SearchJobAsynTask(reqJson.toString(), completeListener, MyConstants.CONNECTION_TIMEOUT, MyConstants.SOCKET_TIMEOUT);
        Utility.showProgressDialog(context);
        loginAsync.execute(MyConstants.JobPortal_REG_URL);

    }

    private DTO getUserData() {

        UserDTO localObject = (UserDTO) UserDAO.getInstance().getRecords(DBHandler.getInstance(this.mActivity).getDBObject(0)).get(0);
        JobPortalDTO dto = new JobPortalDTO();
        dto.setUserName(getText(userNameEdt));
        dto.setMobileNumber(getText(mobileNoEdt));
        dto.setEmailAddress(getText(emailIdEdt));
        dto.setPreferedLocation(getText(preferedlocation));
        dto.setResumeHeadline(getText(reg_resume));
        dto.setSSCPercentage(getText(reg_sscper));
        dto.setBtechPercentage(getText(reg_btech));
        dto.setInterPercentage(getText(reg_inter));
        dto.setKeySkills(getText(KeySkillEdt));
dto.setCampus_emailid(localObject.getEmailId());

        return dto;
    }
    private void saveData(DTO userData) {
        //context.deleteDatabase("security.db");
        JobportalDAo.getInstance().insert(userData, DBHandler.getInstance(context).getDBObject(1));
        //navigateApp();
    }
    private AsyncTaskCompleteListener completeListener = new AsyncTaskCompleteListener() {
        @Override
        public void onAsynComplete(String result) {
            if (result != null) {
                if(Utility.isJSONValid(result)){
                    try {
                        JSONObject object = new JSONObject(result);
                        int code = object.optInt("code");


                        if(code == 100){
                           // Utility.setAuthCode(object.optString("authcode"),RegistrationActivity.this);
                            //saveData(getUserData());;
                            mActivity.pushFragments(MyConstants.TAB_HOME, new Jobportal(), false, true);
                            Utility.showAlert(context, null, " Your ProfileInsert Successfully");
                            return;
                        }else if(code == 101){
                            Utility.showAlert(context, null, "Failed Register");
                        }else{
                            Utility.showAlert(context, null, "Unknown response");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }else{
                    Utility.showAlert(context, null, "Invalid Response contact system admin");
                }

            } else {
                Utility.showAlert(context, "Network problem", "Check your internet connection");
            }
            Utility.hideProgressDialog();
        }
    };


}