package com.application.tak.takapplication.data_access;

import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

import com.application.tak.takapplication.data_model.Adress;
import com.application.tak.takapplication.data_model.Client_V;
import com.application.tak.takapplication.data_model.School;
import com.application.tak.takapplication.data_model.Student_V;
import com.application.tak.takapplication.data_model.User;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by azielinska on 30.05.2017.
 */
public class CreateStudent extends GetJSONData
{
    private static final String URI = Config.SERVER_NAME+ "new_student.php";
    public Student_V newStudent = null;
    public DB_result dbResult = null;
    Context ctx;

    private static final String TAG_RESULTS="new_student";
    private static final String TAG_ID="ID";
    private static final String TAG_LNAME="LNAME";
    private static final String TAG_FNAME="FNAME";
    private static final String TAG_USERNAME="USERNAME";
    private static final String TAG_PHONE_NO="PHONE_NO";
    private static final String TAG_ROLE_ID="ROLE_ID";
    private static final String TAG_CLASS_ID="CLASS_ID";
    private static final String TAG_CITY="CITY";
    private static final String TAG_ROAD="ROAD";
    private static final String TAG_POSTCODE="POSTCODE";
    private static final String TAG_ROAD_NO="ROAD_NO";
    private static final String TAG_CLASS_NAME="CLASS_NAME";
    private static final String TAG_SCHOOL_ID="SCHOOL_ID";
    private static final String TAG_SIGNUP_CODE="SIGNUP_CODE";
    private static final String TAG_SCHOOL_NAME="SCHOOL_NAME";
    private static final String TAG_EXTERN_APP_ID="EXTERN_APP_ID";

    public CreateStudent(Context _ctx)
    {

        super(_ctx);
        ctx = _ctx;
    }

    public boolean InsertStudent(User u)
    {
        execute(new String[]{u.get_LName(),u.get_FName(),u.get_Username(), u.get_PhoneNo(),u.get_IsActive().toString(),u.get_ClassId().toString(), u.get_ExternAppId()});
        return true;
    }

    @Override
    protected String doInBackground(String... params)
    {       String result = "";

        String lname=params[0];
        String fname=params[1];
        String username=params[2];
        String phone_no=params[3];
        String is_active=params[4];
        String class_id = params[5];
        String extern_app_id = params[6];
        try {
            URL url=new URL(URI);
            HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            OutputStream os=httpURLConnection.getOutputStream();

            String data= URLEncoder.encode("lname","UTF-8")+"="+URLEncoder.encode(lname,"UTF-8")+"&"+
                    URLEncoder.encode("fname","UTF-8")+"="+URLEncoder.encode(fname,"UTF-8")+"&"+
                    URLEncoder.encode("username","UTF-8")+"="+URLEncoder.encode(username,"UTF-8")+"&"+
                    URLEncoder.encode("phone_no","UTF-8")+"="+URLEncoder.encode(phone_no,"UTF-8")+"&"+
                    URLEncoder.encode("is_active","UTF-8")+"="+URLEncoder.encode(is_active,"UTF-8")+"&"+
                    URLEncoder.encode("class_id","UTF-8")+"="+URLEncoder.encode(class_id,"UTF-8")+"&"+
            URLEncoder.encode("extern_app_id","UTF-8")+"="+URLEncoder.encode(extern_app_id,"UTF-8")+"&"+
            URLEncoder.encode("application_id","UTF-8")+"="+URLEncoder.encode(Config.ApplicationId,"UTF-8");

            BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
            bufferedWriter.write(data);
            bufferedWriter.flush();

            int statusCode = httpURLConnection.getResponseCode();
            if (statusCode == 200)
            {

                BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null)
                    sb.append(line).append("\n");

                result = sb.toString();
                if(!ProcessData(result))
                {
                    Helper returnData = new Helper();
                    returnData.ProcessData(result);
                    dbResult = returnData.resultset;
                }
                bufferedWriter.close();
            }


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    private boolean ProcessData(String data)
    {
        try
        {
            JSONObject jsonObject = new JSONObject(data.substring(data.indexOf("{"), data.lastIndexOf("}") + 1));
            if(!jsonObject.isNull(TAG_RESULTS))
            {
                JSONArray jsonUser = jsonObject.getJSONArray(TAG_RESULTS);

                if(jsonUser.length() == 1)
                {
                    Student_V student = new Student_V();

                    JSONObject c = jsonUser.getJSONObject(0);
                    School sSchool = new School();
                    com.application.tak.takapplication.data_model.Class sClass = new com.application.tak.takapplication.data_model.Class();
                    student.set_Id(c.getInt(TAG_ID));
                    student.set_LName(c.getString(TAG_LNAME));
                    student.set_FName(c.getString(TAG_FNAME));
                    student.set_Username(c.getString(TAG_USERNAME));
                    student.set_RoleId(c.getInt(TAG_ROLE_ID));
                    student.set_IsActive(1);
                    student.set_PhoneNo(c.getString(TAG_PHONE_NO));
                    student.set_ClassId(c.getInt(TAG_CLASS_ID));
                    sSchool.set_Id(c.getInt(TAG_SCHOOL_ID));
                    sSchool.set_SchoolName(c.getString(TAG_SCHOOL_NAME));
                    sClass.set_Id(c.getInt(TAG_CLASS_ID));
                    sClass.set_ClassName(c.getString(TAG_CLASS_NAME));
                    sClass.set_SignUpCode(c.getInt(TAG_SIGNUP_CODE));
                    sClass.set_SchoolId(c.getInt(TAG_SCHOOL_ID));
                    student.set_School(sSchool);
                    student.set_Class(sClass);


                    newStudent = student;

                    return true;
                }


            }
        }
        catch (Exception ex)
        {

            ex.printStackTrace();
        }

        return false;


    }
}
