/* fetch files from the server and store in bufferedReaders array which is a global variable */
  public boolean FetchFiles(String fileName, int pos) {
    BufferedReader br;
    try {
      GlobalCache.Prefs = getSharedPreferences("label", 0);
      // set credentials so that the app can login into the server
      jcifs.Config.setProperty(
          "jcifs.netbios.wins", GlobalCache.Prefs.getString("IPAddress", GlobalCache.IPAddress));
      jcifs.Config.setProperty(
          "jcifs.smb.client.domain", GlobalCache.Prefs.getString("Domain", GlobalCache.Domain));
      jcifs.Config.setProperty(
          "jcifs.smb.client.username",
          GlobalCache.Prefs.getString("Username", GlobalCache.Username));
      jcifs.Config.setProperty(
          "jcifs.smb.client.password",
          GlobalCache.Prefs.getString("Password", GlobalCache.Password));

      String ILocation = GlobalCache.Prefs.getString("Import", GlobalCache.DownLoadLocation);
      SmbFile smbFile =
          new SmbFile(
              ILocation + "Round " + GlobalCache.savedRoundNum + "/" + fileName); // !!!!!!!!!!!!!!!
      // smb://192.168.12.6/Database/Admin/Devin/test.txt
      // !!!!!!!!!!!!!!!!!!

      br = new BufferedReader(new InputStreamReader(new SmbFileInputStream(smbFile)));

      // Upload a confirmation file
      SmbFile f =
          new SmbFile(
              ILocation + "Round " + GlobalCache.savedRoundNum + "/" + "DownloadConfirmation.txt");
      SmbFileOutputStream out = new SmbFileOutputStream(f, true);
      byte[] msg;
      Calendar c = Calendar.getInstance();
      SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
      String DownloadedDate = df.format(c.getTime());
      msg = (fileName + " - " + DownloadedDate + "\r\n").getBytes("US-ASCII");
      out.write(msg);
      out.close();
    } catch (UnknownHostException e1) {
      return false;
    } catch (SmbException e1) {
      return false;
    } catch (MalformedURLException e1) {
      return false;
    } catch (IOException e1) {
      return false;
    }

    bufferedReaders[pos] = br;

    return true;
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_ui);
    // INITIALIZING VARIABLES TO BE USED LATER AND GUI STUFF
    GlobalCache.Prefs = getSharedPreferences("label", 0);
    GlobalCache.savedRoundID = GlobalCache.Prefs.getInt("RoundID", 0);
    GlobalCache.savedRoundNum = GlobalCache.Prefs.getInt("RoundNo", 0);
    GlobalCache.Depot = GlobalCache.Prefs.getString("Depot", GlobalCache.Depot);
    String DataLoadDate = GlobalCache.Prefs.getString("DataLoadDate", "None");
    UsernameAutoCompleteTextView =
        (AutoCompleteTextView) findViewById(R.id.usernameAutoCompleteTextView);
    PasswordInput = (EditText) findViewById(R.id.PasswordInput);
    startRound = (Button) findViewById(R.id.startRound);
    RoundEdit = (EditText) findViewById(R.id.MainUIRoundEdit);
    DownloadFiles = (Button) findViewById(R.id.downloadFiles);
    DepotName = (TextView) findViewById(R.id.MainUIDepotDisplay);
    AppVersion = (TextView) findViewById(R.id.AppVersion);
    UsernameAutoCompleteTextView.setEnabled(false);
    PasswordInput.setEnabled(false);
    startRound.setEnabled(false);

    DepotName.setText(GlobalCache.Depot);
    AppVersion.setText(
        "App Version: " + GlobalCache.Version + "\nLast Data Load Date: " + DataLoadDate);
    // CheckLoadDataDate(DataLoadDate);
    RoundEdit.setText(Integer.toString(GlobalCache.savedRoundNum));
    RoundEdit.addTextChangedListener(
        new TextWatcher() {
          @Override
          public void afterTextChanged(Editable s) {}

          @Override
          public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

          @Override
          public void onTextChanged(CharSequence s, int start, int before, int count) {
            startRound.setEnabled(false);
            int tempRoundNum;
            if (RoundEdit.getText().toString().equals("")) {
              tempRoundNum = 0;
            } else {
              tempRoundNum = Integer.parseInt(RoundEdit.getText().toString());
            }
            GlobalCache.savedRoundNum = tempRoundNum;
            GlobalCache.Prefs = getSharedPreferences("label", 0);
            GlobalCache.Editor = GlobalCache.Prefs.edit();
            GlobalCache.Editor.putInt("RoundNo", tempRoundNum).commit();
            GlobalCache.Editor.putBoolean("downloaded", false).commit();
          }
        });

    // Create a bluetooth instance if the user wants to connect the printer
    GlobalCache.bluetoothConnection = new BluetoothConnectionUI(this);

    // CHECK TO SEE IF DATABASES CREATED
    // IF THEY HAVE BEEN THEN POPULATE THE AUTOCOMPLETE WITH USERS
    GlobalCache.Prefs = getSharedPreferences("label", 0);
    if (GlobalCache.Prefs.getBoolean("downloaded", false)) {
      populateAutoComplete();
    }

    // ONCLICK LISTENER FOR DOWNLOAD BUTTON
    final Context tempContextMain = this;
    DownloadFiles.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View v) {
            // CHECK TO SEE IF DEVICE IS CONNECTED TO THE WIFI
            ConnectivityManager connManager =
                (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            // TODO change this back
            if (mWifi.isConnected()) {
              DownloadFiles.setEnabled(false);
              final ProgressDialog barProgressDialog = new ProgressDialog(MainUI.this);
              // POPUP TO SHOW PROGRESS OF DOWNLOADED FILES
              barProgressDialog.setTitle("Downloading Files ...");
              barProgressDialog.setMessage("Download in progress ...");
              barProgressDialog.setProgressStyle(barProgressDialog.STYLE_HORIZONTAL);
              barProgressDialog.setProgress(0);
              barProgressDialog.setMax(14);
              barProgressDialog.setCancelable(false);
              barProgressDialog.show();
              // RUN A THREAD SO THAT THE PROGRESS BAR CAN BE UPDATED
              Thread longThread =
                  new Thread(
                      new Runnable() {
                        public void run() {
                          barProgressDialog.setProgress(1);

                          for (int i = 0; i <= 12; i++) {
                            // STORE ALL THE READ IN LINES INTO A BUFFERED READER
                            // AND STORE LINES IN MEMORY ON THE DEVICE
                            if (FetchFiles(GlobalCache.filenames[i] + ".txt", i))
                              WriteToPhoneMemory(
                                  ReadBigStringIn(bufferedReaders[i]), GlobalCache.filenames[i]);
                            barProgressDialog.setProgress((2 + i));
                          }
                          // POPULATE THE LIST OBJECTS
                          populateObjectsFromFiles();

                          barProgressDialog.setProgress(14);
                          barProgressDialog.dismiss();

                          // SEND MESSAGE TO NOTIFY THAT THIS THREAD IS ALMOST COMPLETE
                          Message msg = Message.obtain();
                          msg.what = MESSAGE_ONE;
                          downloadHandler.sendMessage(msg);
                        }
                      });
              longThread.start();
            } else {
              Toast toast =
                  Toast.makeText(tempContextMain, "PLEASE CONNECT TO WIFI", Toast.LENGTH_LONG);
              toast.setGravity(Gravity.CENTER, 0, 0);
              toast.show();
            }
          }
        });

    // login to begin round
    startRound.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View v) {
            GlobalCache.Prefs = getSharedPreferences("label", 0);
            String DataLoadDate = GlobalCache.Prefs.getString("DataLoadDate", "None");
            if (CheckLoadDataDate(DataLoadDate)) {

              String usernameIn = UsernameAutoCompleteTextView.getText().toString();
              int pos = UserStringList.indexOf(usernameIn);
              String passwordIn = PasswordInput.getText().toString();
              final User user;
              // check if username or password is blank
              // also make sure user exists in list (pos)
              if (!usernameIn.equals("") & !passwordIn.equals("") & pos != -1) {
                user = UserDB.getUser(Integer.toString(usersIDs[pos]));
                if (passwordIn.equals(user.Password)) {
                  RoundExport roundExportCheck = RoundExportDB.getData(GlobalCache.savedRoundID);
                  // check if user is the same as the rounds file
                  if (roundExportCheck.EmployeeID == user.EmployeeID) {
                    Toast toast = Toast.makeText(tempContextMain, "WELCOME", Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();
                    GlobalCache.Editor = GlobalCache.Prefs.edit();
                    GlobalCache.Editor.putInt("DriverID", user.EmployeeID).commit();
                    Intent intent = new Intent(tempContextMain, DriverInfoAndPreordersUI.class);
                    finish();
                    startActivity(intent);
                  } else { // if a different driver is on the round display a popup notifying him
                    AlertDialog alertDialog = new AlertDialog.Builder(tempContextMain).create();
                    alertDialog.setCancelable(true);
                    alertDialog.setTitle("Different Driver");
                    alertDialog.setMessage(
                        "You are not the current driver for round "
                            + GlobalCache.savedRoundNum
                            + ", DO YOU WANT TO PROCEED?");
                    alertDialog.setButton(
                        AlertDialog.BUTTON_POSITIVE,
                        "OK",
                        new DialogInterface.OnClickListener() {
                          public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            GlobalCache.Editor = GlobalCache.Prefs.edit();
                            GlobalCache.Editor.putInt("DriverID", user.EmployeeID).commit();

                            GlobalCache.Editor = GlobalCache.Prefs.edit();
                            GlobalCache.Editor.putString("PosInApp", "DriverInfoAndPreordersUI")
                                .commit();

                            Intent intent =
                                new Intent(tempContextMain, DriverInfoAndPreordersUI.class);
                            finish();
                            startActivity(intent);
                          }
                        });
                    alertDialog.setButton(
                        AlertDialog.BUTTON_NEGATIVE,
                        "CANCEL",
                        new DialogInterface.OnClickListener() {
                          public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                          }
                        });

                    alertDialog.show();
                  }
                } else {
                  Toast toast =
                      Toast.makeText(tempContextMain, "INCORRECT LOGIN DETAILS", Toast.LENGTH_LONG);
                  toast.setGravity(Gravity.CENTER, 0, 0);
                  toast.show();
                }
              } else {
                Toast toast =
                    Toast.makeText(tempContextMain, "INCORRECT LOGIN DETAILS", Toast.LENGTH_LONG);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
              }
            }
          }
        });

    // Check if data is old
    if (CheckLoadDataDate(DataLoadDate) == false) {
      final Context context = this;
      Popup popup =
          new Popup(
              context,
              new String[] {
                "Data on tablet is old. Do you want to go to end of day or clear data?",
                "Go to end of day",
                "Clear data"
              },
              new int[] {R.drawable.blue_button, R.drawable.button_reddish},
              false,
              new boolean[] {true, true},
              new Popup.MyCallbackInterface() {
                public void buttonClicked(String buttonName) {
                  if (buttonName.equals("Go to end of day")) {
                    Intent intent = new Intent(context, BankingUI.class);
                    finish();
                    startActivity(intent);
                  } else if (buttonName.equals("Clear data")) {
                    // clear all saved prefs
                    GlobalCache.Editor = GlobalCache.Prefs.edit();
                    GlobalCache.Editor.putString("PosInApp", "MainUI").commit();
                    GlobalCache.Editor.putInt("DriverID", 0).commit();
                    GlobalCache.Editor.putBoolean("BankingPrinted", false).commit();
                    GlobalCache.Editor.putBoolean("downloaded", false).commit();
                    GlobalCache.Editor.putString("PosInApp", "MainUI").commit();
                    GlobalCache.Editor.putString("PosInApp", "MainUI").commit();
                  }
                }
              });
    } else {

      // check if user has already logged in
      // if already logged in then go to relevant activity
      GlobalCache.Prefs = getSharedPreferences("label", 0);
      String PosInApp = GlobalCache.Prefs.getString("PosInApp", "MainUI");
      if (PosInApp.equals("DriverInfoAndPreordersUI")) {
        Intent intent = new Intent(this, DriverInfoAndPreordersUI.class);
        finish();
        startActivity(intent);
      } else if (PosInApp.equals("VehicleStockUI")) {
        Intent intent = new Intent(this, VehicleStockUI.class);
        finish();
        startActivity(intent);
      } else if (PosInApp.equals("DebtorUI")) {
        Intent intent = new Intent(this, DebtorUI.class);
        finish();
        startActivity(intent);
      } else if (PosInApp.equals("BankingUI")) {
        Intent intent = new Intent(this, BankingUI.class);
        finish();
        startActivity(intent);
      } else if (PosInApp.equals("RejectsReturnsCratesUI")) {
        Intent intent = new Intent(this, RejectsReturnsCratesUI.class);
        finish();
        startActivity(intent);
      } else if (PosInApp.equals("EndOfDayUI")) {
        Intent intent = new Intent(this, EndOfDayUI.class);
        finish();
        startActivity(intent);
      }
    }
  }