Lifx.psm1


function Set-LifxApiKey {
param(
    [string] $apiKey
    )

    #$secureString = ConvertTo-SecureString -AsPlainText -Force $apiKey
    #$secureString | ConvertFrom-SecureString | Set-Content LifxApi.key
    $apiKey | Set-Content LifxApi.key
}

function Get-LifxApiKey {
    return Get-Content LifxApi.key
}

function Get-LifxLight {
param(
    [string] $label
    )

    $apiKey = Get-LifxApiKey
    $acceptHeader = "application/json"
    $headers = @{ Authorization = ("Bearer {0}" -f $apiKey) }
    $url = "https://api.lifx.com/v1/lights/all"

    if ($label -ne "") {
        $url = "https://api.lifx.com/v1/lights/label:$label"
    }

    $response = Invoke-RestMethod -headers $headers -uri $url -Method Get -ContentType $acceptheader
    $response
}

function Toggle-LifxLight {
param(
    [string] $label,
    [parameter(ValueFromPipeline)] $Light
    )

    if ($label -ne "") {
        $url = "https://api.lifx.com/v1/lights/label:$label/toggle"
    } else {
        $url = "https://api.lifx.com/v1/lights/id:$($Light.id)/toggle"
    }

    $response = Invoke-RestMethod -headers $headers -uri $url -Method Post -ContentType $acceptheader
    $response
}

function Set-LifxLight {
param(
    [string][ValidateSet(“on”,”off”)]  $Power,
    [string] $Color,
    [double][ValidateRange(0.0,1.0)] $Brightness,
    [double][ValidateRange(0.0,3155760000.0)] $Duration,
    [double][ValidateRange(0.0,1.0)] $infrared,
    [switch] $Fast,
    [parameter(ValueFromPipeline)] $Light
    )

    $payload = @{}

    if ($Power -ne $null) {
        $payload["power"] = $Power
    }

    if ($Color -ne $null) {
        $payload["color"] = $Color
    }

    if ($Brightness -ne $null) {
        $payload["brightness"] = $Brightness
    }

    if ($Duration -ne $null) {
        $payload["duration"] = $Duration
    }

    if ($infrared -ne $null) {
        $payload["infrared"] = $infrared
    }

    if ($Fast) {
        $payload["fast"] = "true"
    }

    
    $url = "https://api.lifx.com/v1/lights/id:$($Light.id)/state"

    $json = $payload | ConvertTo-Json
    
    $response = Invoke-RestMethod -headers $headers -uri $url -Method Put -Body $json -ContentType $acceptheader
    $response
}



Export-ModuleMember -Function 'Set-LifxApiKey'

Export-ModuleMember -Function 'Get-LifxApiKey'

Export-ModuleMember -Function 'Get-LifxLight'

Export-ModuleMember -Function 'Toggle-LifxLight'

Export-ModuleMember -Function 'Set-LifxLight'