master
Scanning / src / Main.elm
-- Copyright © 2023 Dean Lee

module Main exposing (..)

import Browser
import Browser.Events
import Element exposing (..)
import Element.Background as Background
import Element.Border as Border
import Element.Events
import Element.Font as Font
import Element.Input as Input
import Html exposing (Html)
import Http
import Ionicon

main =
  Browser.element
    { init = init
    , update = update
    , subscriptions = subscriptions
    , view = view
    }

type FileType
  = Pdf
  | Jpeg

type Dialog
  = SaveOrDownloadPdf
  | SaveOrDownloadJpeg
  | PdfSaved
  | JpegSaved
  | NoDialog

type alias Model =
  { viewportWidth : Int
  , viewportHeight : Int
  , appUrl : String
  , scanner : String
  , scannerReady : Bool
  , images : List String
  , selectedImage : Maybe Int
  , pdfFile : Maybe String
  , dialog : Dialog
  }

init : { viewportWidth : Int, viewportHeight : Int, url : String } -> (Model, Cmd Msg)
init browserData =
  let appUrl = browserData.url ++ "app/" in
  ( { viewportWidth = browserData.viewportWidth
    , viewportHeight = browserData.viewportHeight
    , appUrl = appUrl
    , scanner = ""
    , scannerReady = False
    , images = []
    , selectedImage = Nothing
    , pdfFile = Nothing
    , dialog = NoDialog
    }
  , Http.get
    { url = appUrl ++ "get-scanner"
    , expect = Http.expectString AddScanner
    }
  )

type Msg
  = UpdateViewport (Int, Int)
  | AddScanner (Result Http.Error String)
  | ScanImage
  | AddImage (Result Http.Error String)
  | SelectImage Int
  | RemoveImage
  | ImageUp
  | ImageDown
  | RotateImage
  | ReplaceImage (Result Http.Error String)
  | SaveImage
  | MakePdf
  | SavePdf String
  | ShowSaveOrDownloadPdfDialog (Result Http.Error String)
  | ShowSaveOrDownloadJpegDialog
  | ShowPdfSavedDialog (Result Http.Error String)
  | ShowJpegSavedDialog (Result Http.Error String)
  | ClearDialog
  | Noop (Result Http.Error String)

update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
  let
    splitList3 : Int -> Int -> List a -> (List a, List a, List a)
    splitList3 middleStart middleLength list =
      ( List.take middleStart list
      , List.drop middleStart list |> List.take middleLength
      , List.drop (middleStart + middleLength) list
      )
  in
  case msg of
    UpdateViewport (width, height) ->
      ( { model | viewportWidth = width, viewportHeight = height }
      , Cmd.none
      )
    AddScanner result ->
      case result of
        Ok scanner ->
          ( { model | scanner = scanner, scannerReady = True }
          , Cmd.none
          )
        Err _ -> ( model, Cmd.none )
    ScanImage ->
      case model.scannerReady of
        True ->
          ( { model | scannerReady = False }
          , Http.get
            { url = model.appUrl ++ "scan/" ++ model.scanner
            , expect = Http.expectString AddImage
            }
          )
        False -> ( model, Cmd.none )
    AddImage result ->
      case result of
        Ok image ->
          ( { model | scannerReady = True, images = model.images ++ [image] }
          , Cmd.none
          )
        Err _ -> ( { model | scannerReady = True }, Cmd.none )
    SelectImage index ->
      ( { model | selectedImage = Just index }, Cmd.none )
    RemoveImage ->
      case model.selectedImage of
        Just index ->
          let
            (listA, _, listC) = splitList3 index 1 model.images
            newImages = listA ++ listC
          in
          ( { model | images = newImages, selectedImage = Nothing }, Cmd.none )
        Nothing -> ( model, Cmd.none )
    ImageUp ->
      case model.selectedImage of
        Just index ->
          if index /= 0 then
            let
              (listA, listB, listC) = splitList3 (index - 1) 2 model.images
              newImages = listA ++ (List.reverse listB) ++ listC
            in
            ( { model | images = newImages, selectedImage = Nothing }, Cmd.none )
          else ( model, Cmd.none )
        Nothing -> ( model, Cmd.none )
    ImageDown ->
      case model.selectedImage of
        Just index ->
          if index /= (List.length model.images) - 1 then
            let
              (listA, listB, listC) = splitList3 index 2 model.images
              newImages = listA ++ (List.reverse listB) ++ listC
            in
            ( { model | images = newImages, selectedImage = Nothing }, Cmd.none )
          else ( model, Cmd.none )
        Nothing -> ( model, Cmd.none )
    RotateImage ->
      case model.scannerReady of
        True ->
          case model.selectedImage of
            Just index ->
              case List.head <| List.drop index model.images of
                Just value ->
                  ( { model | scannerReady = False }
                  , Http.get
                    { url = model.appUrl ++ "rotate/" ++ value
                    , expect = Http.expectString ReplaceImage
                    }
                  )
                Nothing -> ( model, Cmd.none ) 
            Nothing -> ( model, Cmd.none )
        False -> ( model, Cmd.none )
    ReplaceImage result ->
      case result of
        Ok image ->
          case model.selectedImage of
            Just index ->
              let
                (listA, _, listC) = splitList3 index 1 model.images
                newImages = listA ++ [image] ++ listC
              in
              ( { model | scannerReady = True, images = newImages }, Cmd.none )
            Nothing -> ( model, Cmd.none )
        Err _ -> ( { model | scannerReady = True }, Cmd.none )
    SaveImage ->
      case model.selectedImage of
        Just index ->
          case List.head <| List.drop index model.images of
            Just value ->
              ( model
              , Http.get
                { url = model.appUrl ++ "save/" ++ value
                , expect = Http.expectString ShowJpegSavedDialog
                }
              )
            Nothing -> ( model, Cmd.none )
        Nothing -> ( model, Cmd.none )
    MakePdf ->
      let path = model.images |> List.intersperse "/" |> List.foldr (++) "" in
      ( model
      , Http.get
        { url = model.appUrl ++ "pdf/" ++ path
        , expect = Http.expectString ShowSaveOrDownloadPdfDialog
        }
      )
    SavePdf fileName ->
      ( model
      , Http.get
        { url = model.appUrl ++ "save/" ++ fileName
        , expect = Http.expectString ShowPdfSavedDialog
        }
      )
    ShowSaveOrDownloadPdfDialog result ->
      case result of
        Ok fileName ->
          ( { model | dialog = SaveOrDownloadPdf, pdfFile = Just fileName }, Cmd.none )
        Err _ -> ( model, Cmd.none )
    ShowSaveOrDownloadJpegDialog ->
      ( { model | dialog = SaveOrDownloadJpeg }, Cmd.none )
    ShowPdfSavedDialog _ ->
      ( { model | dialog = PdfSaved }, Cmd.none )
    ShowJpegSavedDialog _ ->
      ( { model | dialog = JpegSaved }, Cmd.none )
    ClearDialog ->
      ( { model | dialog = NoDialog, pdfFile = Nothing }, Cmd.none )
    Noop _ ->
      ( model, Cmd.none )

subscriptions : Model -> Sub Msg
subscriptions _ =
  Browser.Events.onResize (\w h -> UpdateViewport (w, h))


-- user interface

-- for use with Ionicon
type alias RGBA =
  { red : Float
  , green : Float
  , blue : Float
  , alpha : Float
  }

primaryButtonColor = rgb255 150 150 255
secondaryButtonColor = rgb255 25 175 25
headerColor = rgb255 230 230 230
mainBackgroundColor = rgb255 50 50 50
primaryTextColor = rgb255 255 255 255

storageName = "LeeData"

dialogSaveOrDownload fileType headerHeight appWidth model =
  let
    fileTypeString =
      case fileType of
        Pdf -> "PDF"
        Jpeg -> "JPEG"
    fileName =
      case fileType of
        Pdf ->
          case model.pdfFile of
            Just pdfFile -> pdfFile
            Nothing -> ""
        Jpeg ->
          case model.selectedImage of
            Just index ->
              case List.head <| List.drop index model.images of
                Just value -> value
                Nothing -> ""
            Nothing -> ""
    buttonAttributes =
      [ height fill
      , Background.color primaryButtonColor
      , Border.rounded <| appWidth // 80
      , Font.size <| appWidth // 20
      , Font.color primaryTextColor
      ]
  in
  [ column
    [ height fill
    , width fill
    , spacing <| appWidth // 40
    ]
    [ Input.button
      (List.append buttonAttributes [ width fill ])
      { onPress =
          case fileType of
            Pdf ->
              case model.pdfFile of
                Just pdfFile -> Just <| SavePdf pdfFile
                Nothing -> Just ClearDialog
            Jpeg -> Just SaveImage
      , label = text <| "Save " ++ fileTypeString ++ " to " ++ storageName
      }
    , row
      [ height fill
      , width fill
      , spacing <| appWidth // 40
      ]
      [ Input.button
        (List.append buttonAttributes [ width fill ])
        { onPress = Nothing
        , label =
          download
          [ height fill
          , width fill
          ]
          { url = "image-cache/" ++ fileName
          , label =
            el
            [ centerX
            , centerY
            ]
            <| text <| "Download " ++ fileTypeString
          }
        }
      , Input.button
        (List.append buttonAttributes [ width <| px <| appWidth // 4 ])
        { onPress = Just ClearDialog
        , label = text "Back"
        }
      ]
    ]
  ]

dialogSaved fileType headerHeight appWidth =
  let
    fileTypeString =
      case fileType of
        Pdf -> "PDF"
        Jpeg -> "JPEG"
  in
  [ column
    [ height fill
    , width fill
    ]
    [ el
      [ centerX
      , centerY
      , Font.size <| appWidth // 16
      ]
      <| text <| fileTypeString ++ " has been saved to " ++ storageName ++ "."
    , Input.button
      [ height <| px <| headerHeight // 3
      , width <| px <| appWidth // 5
      , Background.color primaryButtonColor
      , Border.rounded <| appWidth // 80
      , centerX
      , alignBottom
      , Font.size <| appWidth // 20
      , Font.color primaryTextColor
      ]
      { onPress = Just ClearDialog
      , label = text "OK"
      }
    ]
  ]

globalUI headerHeight appWidth model =
  let
    buttonAttributes =
      [ height fill
      , width fill
      , Background.color primaryButtonColor
      , Border.rounded <| appWidth // 30
      , Font.size <| appWidth // 10
      , Font.color primaryTextColor
      ]
  in
  case model.dialog of
    SaveOrDownloadPdf -> dialogSaveOrDownload Pdf headerHeight appWidth model
    SaveOrDownloadJpeg -> dialogSaveOrDownload Jpeg headerHeight appWidth model
    PdfSaved -> dialogSaved Pdf headerHeight appWidth
    JpegSaved -> dialogSaved Jpeg headerHeight appWidth
    NoDialog ->
      if not model.scannerReady then
        [ text "Waiting for scanner..." ]
      else
        [ Input.button
          buttonAttributes
          { onPress = Just ScanImage
          , label = text "Scan"
          }
        , if not <| List.isEmpty model.images then
            Input.button
            buttonAttributes
            { onPress = Just MakePdf
            , label = text "PDF"
            }
          else none
        ]

imageUI imageWidth =
  let
    imageHeight =
      (toFloat imageWidth) * 1.376 |> round
    buttonSize =
      imageWidth // 6
    localButtonAttributes =
      [ height <| px buttonSize
      , width <| px buttonSize
      , Background.color secondaryButtonColor
      , Border.rounded <| imageWidth // 20
      ]
    makeIcon icon =
      html <| icon buttonSize <| RGBA 1 1 1 1    
  in
  column
  [ height <| px imageHeight
  , width <| px imageWidth
  ]
  [ column
    [ height <| px imageWidth
    , width <| px imageWidth
    , centerY
    , padding <| imageWidth // 10
    ]
    [ row
      [ height <| px buttonSize
      , width fill
      ]
      [ Input.button
        ( centerX :: localButtonAttributes )
        { onPress = Just ImageUp
        , label = makeIcon Ionicon.arrowUpC
        }
      ]
    , row
      [ height <| px buttonSize
      , width fill
      , centerY
      ]
      [ Input.button
        ( alignLeft :: localButtonAttributes )
        { onPress = Just ShowSaveOrDownloadJpegDialog
        , label = makeIcon Ionicon.disc
        }
      , Input.button
        ( centerX :: localButtonAttributes )
        { onPress = Just RotateImage
        , label = makeIcon Ionicon.loop
        }
      , Input.button
        ( alignRight :: localButtonAttributes )
        { onPress = Just RemoveImage
        , label = makeIcon Ionicon.trashA
        }
      ]
    , row
      [ height <| px buttonSize
      , width fill
      , alignBottom
      ]
      [ Input.button
        ( centerX :: localButtonAttributes )
        { onPress = Just ImageDown
        , label = makeIcon Ionicon.arrowDownC
        }
      ]
    ]
  ]

renderImages appWidth model =
  let
    imageWidth =
      appWidth - (appWidth // 10)
    
    renderImage index fileName =
      let
        imageAttributes =
          [ width <| px imageWidth
          , centerX
          , Element.Events.onClick <| SelectImage index
          ]
      in
      image
      (
      case model.selectedImage of
        Nothing ->
          imageAttributes
        Just value ->
          if value == index then
            (Element.inFront <| imageUI imageWidth) :: imageAttributes
          else imageAttributes
      )
      { src = "image-cache/" ++ fileName
      , description = "scanned image"
      }
  in
  List.indexedMap renderImage model.images

viewPrimary : Model -> Element Msg
viewPrimary model =
  let
    headerHeight =
      model.viewportHeight // 5
    appWidth =
      if model.viewportWidth <= 500 then
        model.viewportWidth
      else 500
  in
  column
  [ height fill, width fill ]
  [ row 
    [ height <| px headerHeight
    , width fill
    , Background.color headerColor
    ]
    [ row
      [ height fill
      , width <| px appWidth 
      , centerX
      , padding <| appWidth // 40
      , spacing <| appWidth // 40
      , Font.center
      ]
      <| globalUI headerHeight appWidth model
    ]
  , row
    [ height <| px <| model.viewportHeight - headerHeight
    , width fill
    , scrollbarY
    , Background.color mainBackgroundColor
    ]
    [ column
      [ height fill
      , width <| px appWidth
      , centerX
      , Font.color primaryTextColor
      , paddingXY 0 10
      , spacing 20
      ]
      <| renderImages appWidth model
    ]
  ]

view : Model -> Html Msg
view model =
  let
    style =
      focusStyle
      { borderColor = Nothing
      , backgroundColor = Nothing, shadow = Nothing
      }
  in
  layoutWith { options = [ style ] } [] <| viewPrimary model
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550