namespace SqlDynamite.Common

open System
open Neo4j.Driver

type Neo4jConnection() =
    inherit NoSqlConnection()

    static member GetData(driver:IDriver, script:string) : System.Collections.Generic.List<IRecord> =
        let data = async { return! driver.AsyncSession().RunAsync(script) |> Async.AwaitTask } |> Async.RunSynchronously
        async { return! data.ToListAsync() |> Async.AwaitTask } |> Async.RunSynchronously
    
    override this.Open () =
        let parts = this.ConnectionString.Split(';')
        let url = parts.[0]
        let username = if parts.Length = 3 then parts.[1] else null
        let password = if parts.Length = 3 then parts.[2] else null
        let authToken = if (String.IsNullOrWhiteSpace(password) || String.IsNullOrWhiteSpace(username)) then AuthTokens.None else AuthTokens.Basic(username, password)

        let driver = GraphDatabase.Driver(url, authToken)
        async {ignore(driver.AsyncSession().RunAsync("Match () Return 1 Limit 1") |> Async.AwaitTask)} |> Async.RunSynchronously
        ()

    override this.ServerVersion with get() =
                                     let parts = this.ConnectionString.Split(';')
                                     let url = parts.[0]
                                     let username = if parts.Length = 3 then parts.[1] else null
                                     let password = if parts.Length = 3 then parts.[2] else null
                                     let authToken = if (String.IsNullOrWhiteSpace(password) || String.IsNullOrWhiteSpace(username)) then AuthTokens.None else AuthTokens.Basic(username, password)

                                     let driver = GraphDatabase.Driver(url, authToken)
                                     let script = "call dbms.components() yield versions unwind versions as version return version"
                                     Neo4jConnection.GetData(driver, script).Item(0).Item("version").ToString()