package com.example.database4

import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.widget.TextView
import androidx.activity.ComponentActivity
import java.io.BufferedInputStream
import java.io.File
import java.io.FileOutputStream


class MovieActivity : ComponentActivity() {

    companion object {
        var mContext: Context? = null
    }
    var mDatabase: SQLiteDatabase? = null
    var mBasicInfo: TextView? = null
    var A:ArrayList<String> = ArrayList<String>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        mContext = this
        mBasicInfo = findViewById(R.id.BasicInfo)
        mBasicInfo!!.setMovementMethod(ScrollingMovementMethod())
        val path: String = mContext!!.applicationInfo.dataDir + "/databases/movies.db"
        //The file name of the database in the DATA FOLDER
        println (path)
        /*
        mContext!!.applicationInfo.dataDir is a folder on the Android that an app
        can use to store data.  The data stored remains there so that if the app
        is killed and restarted, the data remains stored there between iterations.

        This is NOT the same as the assets folder which is where you load information
        at programming time.  This dataDir is where you store information during
        runtime.
         */
        /* The first thing I want to do is copy the database from the assets folder
           to the dataDir...if I haven't already done this.
         */
              File (path).delete()//This deletes the copy in the data folder.  You normally would not want to do this.
        if (File(path).exists())
            mBasicInfo!!.text = "EXISTS"
        else {
            mBasicInfo!!.text = "DOES NOT EXIST"
            val assetfile: BufferedInputStream? =
                BufferedInputStream(mContext!!.assets.open("movies.db"))
            //This is the initial database from the assets folder
            try {
                File(mContext!!.applicationInfo.dataDir + "/databases").mkdir()
                //Making the data folder
            } catch (e: Exception) {
            }
            val dbfile: FileOutputStream? = FileOutputStream(path)
            while (true) {  //copying the assets folder into the data directory
                val ch: Int = assetfile!!.read()
                if (ch == -1) break
                dbfile!!.write(ch)
            }
            //copying the skeleton database from the assets folder to the data folder, byte by byte.
            assetfile.close()
            dbfile!!.flush()
            dbfile.close()
        }  //At this point, I know I have a database in the data folder.
        mDatabase = MovieDBHelper().writableDatabase
        //Using MovieDBHelper means I don't have to use the SQLiteHelper with its million parameters
       // mDatabase!!.delete (MovieTable.NAME,"${MovieTable.Cols.TITLE} = 'Akira'",null)
       // mDatabase!!.delete (MovieTable.NAME,"YEAR >= 2000 AND YEAR < 2010",null)
        var values = getAkiraValues()
      //   mDatabase!!.insert (MovieTable.NAME,null,values)
        /*
          var values = getContentValues()

          mDatabase!!.delete (MovieTable.NAME,"${MovieTable.Cols.YEAR} >= 2000",null)

          mDatabase!!.insert (MovieTable.NAME,null,values)
          values = getContentValuesHP ()
          mDatabase!!.insert (MovieTable.NAME,null,values)



                mDatabase!!.insert (MovieTable.NAME,null,getContentValues2())
                mDatabase!!.insert (MovieTable.NAME,null,getContentValues3())
                mDatabase!!.insert (MovieTable.NAME,null,getContentValues4())
                mDatabase!!.insert (MovieTable.NAME,null,getContentValues5())
               var cursor = query ("Year < 2000",null) //Give me a dump of the table

         */
        //mDatabase!!.delete (MovieTable.NAME,"${MovieTable.Cols.TITLE} = 'Akira'",null)
        //mDatabase!!.insert (MovieTable.NAME,null,getAkiraValues())
        /*
        mDatabase!!.insert (MovieTable.NAME,null,getContentValues())
        mDatabase!!.insert (MovieTable.NAME,null,getContentValues3())
        mDatabase!!.insert (MovieTable.NAME,null,getContentValues4())
        mDatabase!!.insert (MovieTable.NAME,null,getContentValuesHP())
    */
       var cursor = query (null,null) //Give me a dump of the table
      //  var cursor = query ("YEAR >= 1980 AND YEAR < 1990",null) //Give me a dump of the table
        //The query doesn't give me that two-dimensional grid.  It gives me a cursor or pointer to a
        //specific row of the grid.
        cursor.moveToFirst()  //the first line of our output grid
        while (!cursor.isAfterLast) {  //Just checks to see if we've processed the whole thing
            val ss = cursor.stuff  //This calls the get method
            mBasicInfo!!.text = mBasicInfo!!.text.toString() + "\r\n${ss.title} ${ss.genre} ${ss.year} ${ss.description} ${ss.id}"
            cursor.moveToNext()
        }
        /*
               mDatabase!!.delete (MovieTable.NAME,"${MovieTable.Cols.YEAR} < 2000",null)
               cursor = query (null,null) //Give me a dump of the table
       //        val cursor = query ("Title = ?",arrayOf<String>("Jurassic Park")) //Give me a dump of the table
       //        val cursor = query ("Year = 1993",null) //Give me a dump of the table
               cursor.moveToFirst()  //the first line of our output grid
               while (!cursor.isAfterLast) {  //Just checks to see if we've processed the whole thing
                   val ss = cursor.stuff
                   println ("${ss.title} ${ss.genre} ${ss.year} ${ss.description} ${ss.id}")
                   A.add ("${ss.title} ${ss.genre} ${ss.year} ${ss.description} ${ss.id}")
                   cursor.moveToNext()
               }
               cursor.close()

         */
        mDatabase!!.close()
    }

    fun query (whereClause:String?,whereArgs:Array<String>?):MovieCursorWrapper {
        val cursor = mDatabase!!.query (MovieTable.NAME,null,whereClause,whereArgs,null,null,null)
        return MovieCursorWrapper (cursor)
    }
    fun getAkiraValues ():ContentValues { //ContentValues is a built-in Kotlin class for use in SQLite databases
        //It's just a wrapper class around a set of column names and column values

        val values = ContentValues ()
        values.put(MovieTable.Cols.TITLE,"Akira")
        values.put(MovieTable.Cols.GENRE,"Anime")
        values.put(MovieTable.Cols.YEAR,1986)
        values.put(MovieTable.Cols.DESCRIPTION,"Gang Wars In Dystopic Future Tokyo")
        return values
    }

    fun getContentValues ():ContentValues { //ContentValues is a built-in Kotlin class for use in SQLite databases
        //It's just a wrapper class around a set of column names and column values

        val values = ContentValues ()
        values.put(MovieTable.Cols.TITLE,"Back To The Future Part II")
        values.put(MovieTable.Cols.GENRE,"Science Fiction")
        values.put(MovieTable.Cols.YEAR,1989)
        values.put(MovieTable.Cols.DESCRIPTION,"Where We've All Gone Before")
        return values
    }
    fun getContentValues2 ():ContentValues { //ContentValues is a built-in Kotlin class for use in SQLite databases
        //It's just a wrapper class around a set of column names and column values

        val values = ContentValues ()
        values.put(MovieTable.Cols.TITLE,"Everything Everywhere All At Once")
        values.put(MovieTable.Cols.GENRE,"Science Fiction")
        values.put(MovieTable.Cols.YEAR,2022)
        values.put(MovieTable.Cols.DESCRIPTION,"The Title Says It All")
        return values
    }
    fun getContentValues3 ():ContentValues { //ContentValues is a built-in Kotlin class for use in SQLite databases
        //It's just a wrapper class around a set of column names and column values

        val values = ContentValues ()
        values.put(MovieTable.Cols.TITLE,"Snakes On A Plane")
        values.put(MovieTable.Cols.GENRE,"Adventure")
        values.put(MovieTable.Cols.YEAR,2006)
        values.put(MovieTable.Cols.DESCRIPTION,"Snakes On A Plane")
        return values
    }
    fun getContentValues4 ():ContentValues { //ContentValues is a built-in Kotlin class for use in SQLite databases
        //It's just a wrapper class around a set of column names and column values

        val values = ContentValues ()
        values.put(MovieTable.Cols.TITLE,"Crazy Rich Asians")
        values.put(MovieTable.Cols.GENRE,"Comedy")
        values.put(MovieTable.Cols.YEAR,2018)
        values.put(MovieTable.Cols.DESCRIPTION,"Sing Along At The Sound of The Gong")
        return values
    }
    fun getContentValuesHP ():ContentValues { //ContentValues is a built-in Kotlin class for use in SQLite databases
        //It's just a wrapper class around a set of column names and column values

        val values = ContentValues ()
        values.put(MovieTable.Cols.TITLE,"Harry Potter And The Sorceror's Stone")
        values.put(MovieTable.Cols.GENRE,"Fantasy")
        values.put(MovieTable.Cols.YEAR,2001)
        values.put(MovieTable.Cols.DESCRIPTION,"An orphan boy sticks it where it doesn't belong.")
        return values
    }
    fun getContentValues5 ():ContentValues { //ContentValues is a built-in Kotlin class for use in SQLite databases
        //It's just a wrapper class around a set of column names and column values

        val values = ContentValues ()
        values.put(MovieTable.Cols.TITLE,"Chasing Amy")
        values.put(MovieTable.Cols.GENRE,"Dark Romantic Comedy")
        values.put(MovieTable.Cols.YEAR,1997)
        values.put(MovieTable.Cols.DESCRIPTION,"One of the Weirdest Movies You Ever Saw")
        return values
    }
}